[英]Jest mock with TypeScript
我有這個簡單的測試文件:
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模擬方法?
您可以使用類型斷言來提示render
為SpyInstance的typescript
const render = ReactDOM.render as any as SpyInstance;
render.mockImplementationOnce(() => { });
...
而不是使用的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.