How do test async components with Jest?

前端 未结 1 893
野的像风
野的像风 2020-12-21 10:13

can anyone tell me how to wait in jest for a mocked promise to resolve when mounting a component that calls componendDidMount()?

class Something         


        
相关标签:
1条回答
  • 2020-12-21 10:25

    Jest has mocks to fake time travelling, to use it in your case, I guess you can change your code in the following style:

    import { API } from 'api';
    import { API as mockAPI } from '__mocks/api';
    
    API.get = jest.fn().mockImplementation(mockAPI.get);
    
    jest.useFakeTimers(); // this statement makes sure you use fake timers
    
    describe('Something Component', () => {
      it('renders after data loads', () => {
        const wrapper = mount(<Something />);
    
        // skip forward to a certain time
        jest.runTimersToTime(1);
    
        expect(mountToJson(wrapper)).toMatchSnapshot();
      });
    });
    

    Alternatively to jest.runTimersToTime() you could also use jest.runAllTimers()

    0 讨论(0)
提交回复
热议问题