Testing React Functional Component with Hooks using Jest

前端 未结 5 1843
傲寒
傲寒 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:10

    So by taking Alex's answer I was able to formulate the following method to test the component.

    describe(' with no props', () => {
      const container = shallow();
      it('should match the snapshot', () => {
        expect(container.html()).toMatchSnapshot();
      });
    
      it('should have an email field', () => {
        expect(container.find('Email').length).toEqual(1);
      });
    
      it('should have proper props for email field', () => {
        expect(container.find('Email').props()).toEqual({
          onBlur: expect.any(Function),
          isValid: false,
        });
      });
    
      it('should have a password field', () => {
        expect(container.find('Password').length).toEqual(1);
      });
    
      it('should have proper props for password field', () => {
        expect(container.find('Password').props()).toEqual({
          onChange: expect.any(Function),
          value: '',
        });
      });
    
      it('should have a submit button', () => {
        expect(container.find('Button').length).toEqual(1);
      });
    
      it('should have proper props for submit button', () => {
        expect(container.find('Button').props()).toEqual({
          disabled: true,
          onClick: expect.any(Function),
        });
      });
    });
    

    To test the state updates like Alex mentioned I tested for sideeffects:

    it('should set the password value on change event with trim', () => {
        container.find('input[type="password"]').simulate('change', {
          target: {
            value: 'somenewpassword  ',
          },
        });
        expect(container.find('input[type="password"]').prop('value')).toEqual(
          'somenewpassword',
        );
      });
    

    but to test the lifecycle hooks I still use mount instead of shallow as it is not yet supported in shallow rendering. I did seperate out the methods that aren't updating state into a separate utils file or outside the React Function Component. And to test uncontrolled components I set a data attribute prop to set the value and checked the value by simulating events. I have also written a blog about testing React Function Components for the above example here: https://medium.com/@acesmndr/testing-react-functional-components-with-hooks-using-enzyme-f732124d320a

提交回复
热议问题