Testing React Functional Component with Hooks using Jest

前端 未结 5 1853
傲寒
傲寒 2020-12-05 06:39

So I\'m moving away from class based components to functional components but am stuck while writing test with jest/enzyme for the methods inside the functional components wh

5条回答
  •  余生分开走
    2020-12-05 07:06

    Currently Enzyme doesn't support React Hooks and Alex's answer is correct, but looks like people (including myself) were struggling with using setTimeout() and plugging it into Jest.

    Below is an example of using Enzyme shallow wrapper that calls useEffect() hook with async calls that results in calling useState() hooks.

    // This is helper that I'm using to wrap test function calls
    const withTimeout = (done, fn) => {
        const timeoutId = setTimeout(() => {
            fn();
            clearTimeout(timeoutId);
            done();
        });
    };
    
    describe('when things happened', () => {
        let home;
        const api = {};
    
        beforeEach(() => {
            // This will execute your useEffect() hook on your component
            // NOTE: You should use exactly React.useEffect() in your component,
            // but not useEffect() with React.useEffect import
            jest.spyOn(React, 'useEffect').mockImplementation(f => f());
            component = shallow();
        });
    
        // Note that here we wrap test function with withTimeout()
        test('should show a button', (done) => withTimeout(done, () => {
            expect(home.find('.button').length).toEqual(1);
        }));
    });
    

    Also, if you have nested describes with beforeEach() that interacts with component then you'll have to wrap beforeEach calls into withTimeout() as well. You could use the same helper without any modifications.

提交回复
热议问题