How to test a react component that is dependent on useContext hook?

前端 未结 6 1913
情话喂你
情话喂你 2020-12-23 13:58

I have a component that uses useContext and then its output is dependent on the value in the context. A simple example:

import React, { useConte         


        
6条回答
  •  一生所求
    2020-12-23 14:32

    What I did is test if useContext was used. In my case, useContext returns function called dispatch.

    In the component I have:

    const dispatch = useContext(...);
    

    and then inside onChange method:

    dispatch({ type: 'edit', payload: { value: e.target.value, name: e.target.name } });
    

    So inside test at the begining:

      const dispatch = jest.fn();
      React.useContext = (() => dispatch) as (context: React.Context) => T;
    

    and then:

      it('calls function when change address input', () => {
       const input = component.find('[name="address"]');
       input.simulate('change', { target: { value: '123', name: 'address' } });
    
       expect(dispatch).toHaveBeenCalledTimes(1);
      });
    

提交回复
热议问题