我如何用玩笑模拟打字稿界面?

时间:2021-03-22 18:23:27

标签: typescript jestjs mocking

我想模拟一个打字稿界面,我该如何实现? 当我获得人类的属性时,我想返回 'Test' 和 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);
   });
});

1 个答案:

答案 0 :(得分:1)

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

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);
  });
});