我想强烈输入我的 Jest 。在某种程度上,我可以让它工作,但是当一个类有私有(private)属性时,我就卡住了。
另一个问题,当我使用模拟时(我目前使用的方式),返回类型是原始类型,但是当我必须访问 Jest 添加的任何方法时,我必须对其进行类型转换,所以 jest.Mock
访问方法。有一个更好的方法吗?我尝试过使用 jest.Mock
, jest.Mocked
, jest.MockInstance
.
如果有人能指出我正确的方向,那就太好了!
class MyTest {
constructor(private readonly msg: string) {}
public foo(): string {
return this.msg;
}
}
const myTestMock: jest.Mock<MyTest, [string]> = jest.fn<MyTest, [string]>(() => ({
msg: 'private',
foo: jest.fn().mockReturnValue('aaa'),
}));
// Results in error:
// Type '{ msg: string; foo: Mock<any, any>; }' is not assignable to type 'MyTest'.
// Property 'msg' is private in type 'MyTest' but not in type '{ msg: string; foo: Mock<any, any>; }'
const myTestMockInstance: MyTest = new myTestMock('a');
console.log(myTestMockInstance.foo()); // --> aaa
// Accessing jest mock methods:
(<jest.Mock>myTestMockInstance).mockClear(); // <-- can this be done without type casting
肮脏的解决方法:
const myTestMock: jest.Mock<MyTest, [string]> = jest.fn<MyTest, [string]>(
// Cast to any to satisfy TS
(): any => ({
msg: 'private',
foo: jest.fn().mockReturnValue('aaa'),
})
);
最佳答案
有一个库可以帮助您在 Typescript with Jest 中使用强类型模拟:jest-mock-extended
我不确定您是否应该访问模拟的私有(private)属性。正如 Kim Kern 所说,您应该只对被测单元的依赖项的公共(public)接口(interface)感兴趣。
jest-mock-extended 包含一个 mock()
返回 MockProxy
的方法允许您访问 .mockReturnValue()
等等
import { mock } from "jest-mock-extended";
interface WidgetService {
listMyWidgets(): { id: string }[];
};
const mockedService = mock<WidgetService>();
mockedService.listMyWidgets.mockReturnValue([{ id: 'widget-1' }]);
关于typescript - 如何强输入 Jest 模拟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54941990/