开玩笑的typescript属性嘲笑在类型上不存在 [英] jest typescript property mock does not exist on type
问题描述
使用jest.fn()
添加模拟时,通常可以访问.mock
属性以访问诸如呼叫之类的详细信息,类似于以下内容:
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:
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
});
当使用打字稿而不是普通的javascript实现测试时,出现错误:
When implementing the test in typescript instead of plain javascript I get the error:
错误TS2339:类型'((callback:()=> number)=> void')不存在属性'mock'.
error TS2339: Property 'mock' does not exist on type '(callback: () => number) => void'.
我可以通过强制转换为any
来消除错误,但是肯定有更好的方法:
I can get rid of the error by casting to any
but surely there must be a better way:
const callback = (foo.addListener as any).mock.calls[0][0];
在这个简单的代码中,可以使用jest.fn(fn => { callback = fn; });
重写模拟程序以存储参数,但是使用foo.addListener.mockClear()
时会发生相同的错误,无法以相同的方式进行修改.
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.
那么如何摆脱错误,最好在不丢失类型安全的情况下呢?
So how can I get rid of the error, preferably without losing type-safety?
推荐答案
您可以将 jest.spyOn
与<一个href ="https://jestjs.io/docs/en/mock-function-api#mockfnmockimplementationfn" rel ="noreferrer"> 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
});
这篇关于开玩笑的typescript属性嘲笑在类型上不存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!