简体   繁体   中英

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'"

Anyone knows how I can make TypeScript recognize jest mock methods?

You can use type assertion to hint typescript that render is a SpyInstance

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() .

const reactRenderMock = jest.spyOn(ReactDOM, 'render');
// ...
reactRenderMock.mockImplementationOnce(() => {} );
// ...
reactRenderMock.render.mockRestore();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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