将Typescript与Jest一起使用时,如何测试超级调用?

时间:2018-12-27 14:55:20

标签: typescript mocking jestjs ts-jest

说我有一个结构如下的班级:

// Some class that calls super.get() and adds an additional param
export default class ClassB extends ClassA {
   private foo: string;

   constructor(params) {
      super(params);
      this.foo = 'bar';
   }

   public async get(params?: { [key: string]: any }): Promise<any> {
      return super.get({
         foo: this.foo,
         ...params,
      });
   }
}

我想测试是否使用提供的参数以及附加的 {foo:'bar'} 调用了super.get()。

import ClassA from '../../src/ClassA';
import ClassB from '../../src/ClassB';

jest.mock('../../src/ClassA');
jest.unmock('../../src/ClassB');

describe('ClassB', () => {
   describe('get', () => {
      beforeAll(() => {
        // I've tried mock implementation on classA here but didn't have much luck
        // due to the extending not working as expected 
      });
      it('should get with ClassA', async () => {
         const classB = new ClassB();
         const response = await classB.get({
           bam: 'boozled',
         });
         // Check if classA fetch mock called with params?
      });
   });
});

我如何检查classA.fetch实际上是用我期望的参数调用的?

我在做完全错误的事情吗?

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

您可以通过监视扩展类的prototype来完成此操作,如下所示:

const classASpy = jest.spyOn(ClassA.prototype, 'get');
classB.get(param)
expect(classASpy).toHaveBeenCalledWith(param);

希望有帮助!