Reactjs 为什么我总是得到';收到的呼叫数:0';我的React单元测试出错?
我是React单元测试新手,在尝试测试表单提交时是否调用了Reactjs 为什么我总是得到';收到的呼叫数:0';我的React单元测试出错?,reactjs,unit-testing,jestjs,Reactjs,Unit Testing,Jestjs,我是React单元测试新手,在尝试测试表单提交时是否调用了handleSubmit方法时,我不断遇到错误:Received calls:0: 错误: Expected number of calls: 1 Received number of calls: 0 9 | const form = wrapper.find('form'); 10 | form.simulate('submit'); > 11 | ex
handleSubmit
方法时,我不断遇到错误:Received calls:0
:
错误:
Expected number of calls: 1
Received number of calls: 0
9 | const form = wrapper.find('form');
10 | form.simulate('submit');
> 11 | expect(onSubmitFn).toHaveBeenCalledTimes(1);
Form.test.js:
import React from "react";
import {shallow } from 'enzyme';
import Form from './Form';
it('calls handleSubmit function on form submission', () => {
const onSubmitFn = jest.fn();
const wrapper = shallow(<Form onSubmit={onSubmitFn} />);
const form = wrapper.find('form');
form.simulate('submit');
expect(onSubmitFn).toHaveBeenCalledTimes(1);
})
从“React”导入React;
从“酶”导入{shall};
从“./Form”导入表单;
它('在表单提交时调用handleSubmit函数',()=>{
const onSubmitFn=jest.fn();
常量包装器=浅();
const form=wrapper.find('form');
形式。模拟(“提交”);
预期(在提交fn)。已被催收时间(1);
})
Form.js:
import React from 'react';
class Form extends React.Component {
render() {
return (
<form onSubmit={this.props.handleSubmit}>
<div>
<div className="field">
<label className="label">Postcode</label>
<input className="input" type="text" onChange={this.props.handleInputChange} required />
</div>
<div className="field">
<div className="control">
<input type='submit' value='Search' />
</div>
</div>
</div>
</form>
)
}
}
export default Form;
从“React”导入React;
类形式扩展了React.Component{
render(){
返回(
邮政编码
)
}
}
导出默认表单;
Tile.js,包括Form.js:
import React from 'react';
import Form from './Form';
class Tile extends React.Component {
.
.
.
handleSubmit(e) {
e.preventDefault();
if (this.handleValidation()) {
this.getCoord();
this.setState({ error: false })
}
else {
this.setState({ error: true });
};
}
.
.
.
render() {
return (
<div>
<Form handleSubmit={this.handleSubmit}/>
</div>
)
}
从“React”导入React;
从“./Form”导入表单;
类扩展了React.Component{
.
.
.
handleSubmit(e){
e、 预防默认值();
if(this.handleValidation()){
这个.getCoord();
this.setState({error:false})
}
否则{
this.setState({error:true});
};
}
.
.
.
render(){
返回(
)
}
有什么帮助吗?这个道具叫做
handleSubmit
:
<form onSubmit={this.props.handleSubmit}>
应该是:
shallow(<Form handleSubmit={onSubmitFn} />);
shall();