【发布时间】:2017-05-06 22:22:53
【问题描述】:
我正在测试一个名为 handleSubmit 的组件方法(名称无关紧要......)。
测试
// ...imported all modules at the top, including enzyme
it('should submit form data', () => {
let form = shallow(<Form />);
let handleSubmit = jest.fn(); // <= this doesn't work!!
form.find('.submit-btn').simulate('click');
expect(form.find('.submit-btn').length).toEqual(1);
expect(handleSubmit).toHaveBeenCalled();
});
组件
import React, { Component } from 'react';
import axios from 'axios';
class CarnetSidebarForm extends Component {
constructor(props) {
super(props);
this.state = {
title: ''
};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(e) {
const target = e.target;
const value = target.value;
const name = target.name;
this.setState({
[name]: value
});
}
handleSubmit(e) {
e.preventDefault();
let payload = {
title: this.state.title
};
this.postCard(payload);
console.log('Payload: ', payload);
}
postCard(data) {
return axios.post('http://localhost:4000/api/cards', data)
.then(response => {
console.log('Response: ', response.message);
});
}
render() {
return (
<div className="card-form-panel">
<form className="card-form" onSubmit={this.handleSubmit}>
<div className="form-group">
<label htmlFor="card-title-field">Title</label>
<input className="form-control"
type="text"
placeholder="Title..."
id="card-title-field"
name="title"
value={this.state.title}
onChange={this.handleChange} />
</div>
<input className="card-submit-btn btn btn-primary" type="submit" value="Save" />
</form>
</div>
);
}
}
export default CarnetSidebarForm;
我不断收到此错误消息,现在很烦人:
expect(jest.fn()).toHaveBeenCalled()
Expected mock function to have been called.
但是如果我在测试中创建一个假组件,那么它就可以工作
it('should submit form data', () => {
let handleSubmit = jest.fn();
// create a fake component
let form = mount(
<form onSubmit={handleSubmit}>
<input className="submit-btn" type="submit" value="Save" />
</form>
);
form.find('.submit-btn').simulate('submit');
expect(form.find('.submit-btn').length).toEqual(1);
expect(handleSubmit).toHaveBeenCalled();
});
与enzyme 中的shallow() 或mount 与导入组件有关吗?我花了很多天寻找答案,但我迷路了。
【问题讨论】:
-
你不应该将
handleSubmit作为道具传递吗?您正在设置handleSubmit但未在您的组件中使用它! -
@Shaoz 你能发布你的组件的最小代码吗?您是将
handleSubmit传递为prop还是组件方法? -
@HardikModha,感谢您的回复。
handleSubmit是一个组件方法。我已经用组件代码更新了我的问题。 -
感谢您的更新。您需要按照@rauliyohmc 的建议模拟组件方法。你试过了吗?
-
@HardikModha,是的,试试他的建议,但我仍然遇到同样的错误
Expected mock function to have been called.所以我认为shallow或mount和jest.fn()有问题。
标签: javascript unit-testing reactjs jestjs