我对 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");
});
我将放弃这里的第一个解决方案 Simulate a button click in Jest 并且:https://facebook.github.io/jest/docs/en/mock-functions.html
编辑:运行上面的代码会引发以下错误:
TypeError: Cannot read property 'value' of undefined
最佳答案
我认为代码片段的语法应该是:
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');
});
关于reactjs - 在 Jest 中测试 onChange 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48180499/