Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 224
Kizer Avatar asked Jun 18 '18 07:06

Kizer


2 Answers

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

const render = ReactDOM.render as any as SpyInstance;
render.mockImplementationOnce(() => { });
...
like image 120
Aleksey L. Avatar answered Oct 21 '22 20:10

Aleksey L.


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();
like image 25
Romain Deneau Avatar answered Oct 21 '22 18:10

Romain Deneau