typescript - 如何用 jest 模拟打字稿界面?
问题描述
我想模拟一个打字稿界面,我该如何实现?当我获得人类的属性时,我想返回“测试”和 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);
});
});
解决方案
name
您正在为和属性返回模拟函数status
,但它们不是函数类型。您应该为接口的这两个属性返回string
和。enum
Human
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);
});
});
推荐阅读
- google-cloud-sql - How connect tot Google Cloud SQL via Exposed
- autodesk-forge - 无法通过 forge-apis 获取一些 BIM360 文件夹
- mysql - 使用 ngrok 公开 mysql 并使用 Datagrip (WSL2) 连接
- python - 创建版本失败。检测到错误模型错误:“...没有名为 'sklearn.impute._base' 的模块;'sklearn.impute' 不是包。(错误代码:0)”
- javascript - 使用 AsyncStorage 推送到数组
- javascript - 具有动态宽度的裁剪 div 的 clientWidth 值不正确(使用 useLayoutEffect 和 SSR)
- ag-grid - 如何在 AG-grid 中创建具有相同名称的不同员工的不同行组?
- laravel - 如何解决 ErrorException:找不到必需的 @OA\PathItem()
- c++ - VkSurfaceKHR 指针的值在没有任何显式赋值的函数调用后发生变化
- haskell - Applying an existentially typed function to a sufficiently polymorphic argument