Mic*_*ael 11 typescript jestjs typescript-typings ts-jest
我想强烈地打我的笑话。在某种程度上,我可以使它工作,但是当一个类具有私有属性时,我就被卡住了。
另一个问题是,当我使用模拟(当前使用的方式)时,返回类型是原始类型,但是当我必须访问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
Run Code Online (Sandbox Code Playgroud)
变通方法:
const myTestMock: jest.Mock<MyTest, [string]> = jest.fn<MyTest, [string]>(
// Cast to any to satisfy TS
(): any => ({
msg: 'private',
foo: jest.fn().mockReturnValue('aaa'),
})
);
Run Code Online (Sandbox Code Playgroud)
小智 7
有一个库可以帮助您使用 Jest 在 Typescript 中进行强类型模拟:jest-mock-extended
我不确定您应该访问模拟的私有属性。正如 Kim Kern 所说,您应该只对被测单元的依赖项的公共接口感兴趣。
jest-mock-extended 包含一个mock()返回 a 的方法MockProxy,该方法允许您访问.mockReturnValue()等。
import { mock } from "jest-mock-extended";
interface WidgetService {
listMyWidgets(): { id: string }[];
};
const mockedService = mock<WidgetService>();
mockedService.listMyWidgets.mockReturnValue([{ id: 'widget-1' }]);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1301 次 |
| 最近记录: |