4

假设我有一个结构如下的课程:

// 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 是否实际上是使用我期望的参数调用的?

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

谢谢你的帮助!

4

1 回答 1

5

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

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

希望能帮助到你!

于 2019-07-10T17:54:27.037 回答