React Enzyme - Test `componentDidMount` Async Call

后端 未结 3 2027
迷失自我
迷失自我 2020-12-09 11:28

everyone.

I\'m having weird issues with testing a state update after an async call happening in componentDidMount.

Here\'s my component code:

3条回答
  •  -上瘾入骨i
    2020-12-09 12:23

    Give you my solution:

    • enzyme 3.9.0
    • enzyme-adapter-react-16 1.9.1
    • react 16.8.0
    • jest

    1- Mock data service

    You must mock the data service (usually something like axios or an other HTTP library).

    File: __mocks__/LogDataService.js:

    let searchData = {}
    
    const LogDataService = {
        search: () => new Promise((resolve, reject) =>
            process.nextTick(() => resolve(searchData))
        ),
        setSearchData: (data) => searchData = data
    }
    
    export default LogDataService
    

    2- Tests

    File: __tests__/toto.test.js:

    jest.mock('services/LogDataService')
    
    import LogDataService from 'services/LogDataService';
    
    // Declare a super promise that will synchro all promises
    function flushPromises() {
        return new Promise(resolve => setImmediate(resolve));
    }
    
    it('renders without data', async () => {
        // Set dummy data
        LogDataService.setSearchData([])
        // The component we want to test that use
        // LogDataService.search method we just mock up
        const component = mount();
        // wait
        await flushPromises();
        // re-build the render
        component.update()
        // Compare to snapshot
        expect(toJson(component)).toMatchSnapshot();
    });
    

提交回复
热议问题