最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Jest mock with TypeScript - Stack Overflow

programmeradmin1浏览0评论

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?

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?

Share Improve this question edited Jun 19, 2018 at 16:50 Kizer asked Jun 18, 2018 at 7:24 KizerKizer 1,6662 gold badges17 silver badges24 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 4

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) 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();
发布评论

评论列表(0)

  1. 暂无评论