【发布时间】:2018-06-19 05:09:13
【问题描述】:
我对 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
【问题讨论】: