小编典典

在Jest中测试onChange函数

reactjs

我对Jest和测试来说相对较新。我有一个带有输入元素的组件:

import * as React from "react";

export interface inputProps{
    placeholder: string;
    className: string;
    value: string;
    onSearch: (depID: string) => void;
}

onSearch(event: any){
    event.preventDefault();
    //the actual onclick event is in another Component
    this.props.onSearch(event.target.value.trim());
}

export class InputBox extends React.Component<inputProps, searchState> {
  render() {
        return (
            <input
                onChange={this.onSearch} //need to test this
                className={this.props.className} 
                type="text"
                value={this.props.value}
                placeholder={this.props.placeholder} />
        );
    }
}

我想要一个测试来检查输入元素的onChange功能是否以输入元素的value属性作为参数。这是我到目前为止所走的距离:

//test to see the input element's onchange 
//returns a function that takes its value as a param
it("onChange param is the same value as the input value", () => {
    const mockFn = jest.fn();
    const input = enzyme.shallow(<InputBox 
                                    value="TestVal"
                                    placeholder="" 
                                    className="" 
                                    onSearch={mockFn}/>);


       input.find('input').simulate('change',  { preventDefault() {} });
       expect(mockFn.mock.calls).toBe("TestVal");
    });

我从这里的第一个解决方案开始模拟Jest
And中的按钮单击https : //facebook.github.io/jest/docs/en/mock-
functions.html

编辑:运行以上会引发以下错误:

 TypeError: Cannot read property 'value' of undefined

阅读 1462

收藏
2020-07-22

共1个答案

小编典典

我认为您代码段的语法应该是:

import React from 'react';

export default class InputBox extends React.Component {
  onSearch(event) {
    event.preventDefault();
    this.props.onSearch(event.target.value.trim());
  }
  render () { return (<input onChange={this.onSearch.bind(this)} />); }
}

测试失败,因为与preventDefault在事件对象上定义函数相同,还必须定义函数上使用的其他属性onSearch

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

先前的测试代码需要定义事件形状,因为您使用的是浅层渲染。如果您想测试onSearch函数上是否使用了实际的输入值,则需要尝试使用以下命令进行完全渲染enzyme.mount

it('should call onChange prop with input value', () => {
  const onSearchMock = jest.fn();
  const component = enzyme.mount(<InputBox onSearch={onSearchMock} value="custom value" />);
  component.find('input').simulate('change');
  expect(onSearchMock).toBeCalledWith('custom value');
});
2020-07-22