Testing onChange function in Jest

前端 未结 5 2161
悲哀的现实
悲哀的现实 2021-02-01 04:07

I\'m relatively new to Jest and testing in general. I have a component with an input element:

import * as React from \"react\";

export interface inputProps{
            


        
5条回答
  •  渐次进展
    2021-02-01 04:36

    Syntax on your code snippet I think should be:

    import React from 'react';
    
    export default class InputBox extends React.Component {
      onSearch(event) {
        event.preventDefault();
        this.props.onSearch(event.target.value.trim());
      }
      render () { return (); }
    }
    

    The test is failing because, as same you define the preventDefault function on the event object, you also must define other properties used on the onSearch function.

    it('should call onChange prop', () => {
      const onSearchMock = jest.fn();
      const event = {
        preventDefault() {},
        target: { value: 'the-value' }
      };
      const component = enzyme.shallow();
      component.find('input').simulate('change', event);
      expect(onSearchMock).toBeCalledWith('the-value');
    });
    

    Previous test code needs to define the event shape because you are using shallow rendering. If you want instead to test that the actual input value is being used on your onSearch function you need to try a full render with enzyme.mount:

    it('should call onChange prop with input value', () => {
      const onSearchMock = jest.fn();
      const component = enzyme.mount();
      component.find('input').simulate('change');
      expect(onSearchMock).toBeCalledWith('custom value');
    });
    

提交回复
热议问题