[英]Jest mock with TypeScript
I have this simple test file: 我有这个简单的测试文件:
describe('index', () => {
it('should bootstrap the app', async () => {
const root = <div />;
jest.spyOn(ReactDOM, 'render');
...
ReactDOM.render.mockImplementationOnce(() => {} );
...
ReactDOM.render.mockRestore();
} );
} );
I get the following typescript error: "TS2339: property 'mockImplementationOnce' does not exist on type 'Renderer'" 我收到以下打字稿错误:“TS2339:属性'mockImplementationOnce'在'Renderer'类型上不存在”
Anyone knows how I can make TypeScript recognize jest mock methods? 任何人都知道如何使TypeScript识别jest模拟方法?
You can use type assertion to hint typescript that render
is a SpyInstance 您可以使用类型断言来提示
render
为SpyInstance的typescript
const render = ReactDOM.render as any as SpyInstance;
render.mockImplementationOnce(() => { });
...
Instead of using ReactDOM.render
which doesn't have the proper type, use the returned value of jest.spyOn(ReactDOM, 'render')
which is a Jest mock function (cf. spyOn()
doc ) ie with the expected type for TypeScript, including both methods mockImplementationOnce()
and mockRestore()
. 而不是使用的
ReactDOM.render
不具有正确的类型,使用的返回值jest.spyOn(ReactDOM, 'render')
这是一个玩笑模拟功能(参见spyOn()
DOC ),即与预期的类型TypeScript,包括mockImplementationOnce()
和mockRestore()
。
const reactRenderMock = jest.spyOn(ReactDOM, 'render');
// ...
reactRenderMock.mockImplementationOnce(() => {} );
// ...
reactRenderMock.render.mockRestore();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.