我有这个简单的测试文件:
describe('index', () => {
it('should bootstrap the app', async () => {
const root = <div />;
jest.spyOn(ReactDOM, 'render');
...
ReactDOM.render.mockImplementationOnce(() => {} );
...
ReactDOM.render.mockRestore();
} );
} );
我收到以下打字稿错误:“TS2339:属性'mockImplementationOnce'在'Renderer'类型上不存在”
任何人都知道如何让TypeScript识别出jest模拟方法?
答案 0 :(得分:2)
您可以使用type assertion提示render
为SpyInstance
const render = ReactDOM.render as any as SpyInstance;
render.mockImplementationOnce(() => { });
...
答案 1 :(得分:0)
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) i.e. with the expected type for TypeScript, including both methods mockImplementationOnce()
and mockRestore()
.
const reactRenderMock = jest.spyOn(ReactDOM, 'render');
// ...
reactRenderMock.mockImplementationOnce(() => {} );
// ...
reactRenderMock.render.mockRestore();