【问题标题】:How do I test super calls when using Typescript with Jest?将 Typescript 与 Jest 一起使用时如何测试超级调用?
【发布时间】:2019-05-25 14:17:07
【问题描述】:

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

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

我做错了什么吗?

感谢您的帮助!

【问题讨论】:

    标签: typescript mocking jestjs ts-jest


    【解决方案1】:

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

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

    希望对你有帮助!

    【讨论】:

    • 为了保持干净,您还应该在测试后致电classASpy.mockClear();
    • 如何验证构造函数?
    • 什么意思?,要测试构造函数,你应该创建一个新的类实例,这个答案可能对你有帮助stackoverflow.com/questions/48219267/…
    猜你喜欢
    • 1970-01-01
    • 2021-10-27
    • 2019-12-28
    • 2018-08-09
    • 2019-06-08
    • 1970-01-01
    • 2021-03-28
    • 1970-01-01
    • 2020-09-04
    相关资源
    最近更新 更多