Testing onChange function in Jest

前端 未结 5 2063
悲哀的现实
悲哀的现实 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:24

    For those testing using TypeScript (and borrowing from the answers above), you'll need to perform a type coercion (as React.ChangeEvent) to ensure that the linter can view the signature as being compatible:

    React file

    export class InputBox extends React.Component {
      onSearch(event: React.ChangeEvent){
        event.preventDefault();
        //the actual onclick event is in another Component
        this.props.onSearch(event.target.value.trim());
      }
    
      render() {
        return (
          
          );
      }
    }
    

    Test file

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

    or alternatively

    it('should call onChange prop', () => {
      const onSearchMock = jest.fn();
      const event = {
        target: { value: 'the-value' }
      } as React.ChangeEvent;
      const component = enzyme.mount();
      const instance = component.instance();
      instance.onSearch(event);
      expect(onSearchMock).toBeCalledWith('the-value');
    });
    

提交回复
热议问题