繁体   English   中英

使用TypeScript进行Jest模拟

[英]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模拟方法?

您可以使用类型断言来提示renderSpyInstance的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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM