【发布时间】:2019-07-23 07:55:57
【问题描述】:
我想强烈键入我的笑话。在某种程度上,我可以让它工作,但是当一个类有私有属性时,我就卡住了。
另外一个问题,当我使用模拟时(我目前使用的方式),返回类型是原始类型,但是当我必须访问 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'),
})
);
【问题讨论】:
-
私有属性有什么问题? IMO 你应该只模拟(和测试)公共接口。你看过这篇文章吗? patrickdesjardins.com/blog/…
-
@KimKern 问题是打字稿抛出错误,因为模拟不包含私有属性,所以我的模拟与我试图模拟的类型不匹配。
-
感谢您的链接,有趣的文章虽然我认为这是一种解决方法,但它可能是目前最好的选择。我希望 jest 已经有办法做到这一点,而不是创建自己的别名。
-
是的,这绝对只是一种解决方法。 :/我正在使用它,但我也遇到了这种方法的问题。但是由于 jest 正在为下一个主要版本迁移到 typescript,我希望这会变得更好。另见github.com/facebook/jest/issues/7832
标签: typescript jestjs typescript-typings ts-jest