jest typescript 属性模拟在类型上不存在
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/52457575/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jest typescript property mock does not exist on type
提问by ext
When using jest.fn()
to add a mock you can usually access the .mock
property to access details such as calls, something similar to this:
使用jest.fn()
添加模拟时,您通常可以访问该.mock
属性以访问调用等详细信息,类似于以下内容:
test('not working', () => {
const foo = new Foo();
foo.addListener = jest.fn();
foo.func(); // will call addListener with a callback
const callback = foo.addListener.mock.calls[0][0];
expect(callback()).toEqual(1); // test the callback
});
When implementing the test in typescript instead of plain javascript I get the error:
当在打字稿而不是普通的 javascript 中实现测试时,我收到错误:
error TS2339: Property 'mock' does not exist on type '(callback: () => number) => void'.
错误 TS2339:属性 'mock' 在类型 '(callback: () => number) => void' 上不存在。
I can get rid of the error by casting to any
but surely there must be a better way:
我可以通过强制转换来摆脱错误,any
但肯定有更好的方法:
const callback = (foo.addListener as any).mock.calls[0][0];
In this simple code the mock could be rewritten to store the argument using jest.fn(fn => { callback = fn; });
but the same error happens when using foo.addListener.mockClear()
which cannot be reworked the same way.
在这个简单的代码中,可以重写模拟来存储参数 usingjest.fn(fn => { callback = fn; });
但在 using 时会发生相同的错误,foo.addListener.mockClear()
而不能以相同的方式重新编写。
So how can I get rid of the error, preferably without losing type-safety?
那么我怎样才能摆脱错误,最好在不失去类型安全的情况下呢?
回答by Brian Adams
You can use jest.spyOn
in combination with functions like mockImplementation
to mock a function while preserving type safety in TypeScript:
您可以jest.spyOn
与类似mockImplementation
模拟函数的函数结合使用,同时在 TypeScript 中保留类型安全性:
class Foo {
addListener = (callback: () => number) => { }
func = () => {
this.addListener(() => 1);
}
}
test('working', () => {
const foo = new Foo();
const mockAddListener = jest.spyOn(foo, 'addListener'); // spy on foo.addListener
mockAddListener.mockImplementation(() => { }); // replace the implementation if desired
foo.func(); // will call addListener with a callback
const callback = mockAddListener.mock.calls[0][0];
expect(callback()).toEqual(1); // SUCCESS
});
回答by gztomas
For anyone getting here, a bit better than casting to any
might be casting as jest.Mock
对于到达这里的任何人来说,比投射到any
可能会投射为 jest.Mock 好一点
const callback = (foo.addListener as jest.Mock).mock.calls[0][0];