我想强烈输入我的笑话。在某种程度上,我可以让它工作,但是当一个类有私有属性时,我就卡住了。
另一个问题,当我使用模拟(我目前的方式)时,返回类型是原始类型,但是当我必须访问 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'),
})
);