【问题标题】:How can i mock a typescript interface with jest?如何用 jest 模拟打字稿界面?
【发布时间】:2021-03-25 10:18:49
【问题描述】:

我想模拟一个打字稿界面,我该如何实现? 当我获得人类的属性时,我想返回“测试”和 ALIVE。 我在尝试编译下面给定的代码时遇到了困难。

错误

TS2345: Argument of type '() => void' is not assignable to parameter of type '() => Human'.   Type 'void' is not assignable to type 'Human'.

示例代码

enum STATUS
{
   DEAD,
   ALIVE
}
    
export interface Human {
   name: string;
   status: STATUS.ALIVE | STATUS.DEAD;
};
  
describe('Human', () => {
   const mock = jest.fn<Human,[]>(() => {
    name   : jest.fn(() => { return 'Test' });
    status : jest.fn(() => { return STATUS.ALIVE });
});

it('should return properties',() => {
    console.log(human.name);
    console.log(human.status);
   });
});

【问题讨论】:

    标签: typescript jestjs mocking


    【解决方案1】:

    您正在返回 namestatus 属性的模拟函数,但它们是 NOT 函数类型。对于Human 接口的这两个属性,您应该返回stringenum

    enum STATUS {
      DEAD,
      ALIVE,
    }
    
    export interface Human {
      name: string;
      status: STATUS.ALIVE | STATUS.DEAD;
    }
    
    describe('Human', () => {
      const mock = jest.fn<Human, []>(() => {
        return {
          name: 'Test',
          status: STATUS.ALIVE,
        };
      });
    
      it('should return properties', () => {
        const human = mock();
        expect(human.name).toEqual('Test');
        expect(human.status).toEqual(STATUS.ALIVE);
      });
    });
    

    【讨论】:

      猜你喜欢
      • 2019-02-06
      • 2020-04-28
      • 2015-09-06
      • 2019-09-24
      • 2016-06-21
      • 2021-12-07
      • 2018-02-04
      • 2018-05-25
      • 1970-01-01
      相关资源
      最近更新 更多