我在为我的前端组件编写mocha测试规范时遇到了很多麻烦。 我的组件看起来很简单,但不知道如何编写测试规范。 有人可以帮我这个吗? 任何帮助将不胜感激! 感谢
import React from 'react';
//Submit handler takes the message and gives it to the callback of its parent component, ChatApp for rendering and emitting to server
//Keep track of the mssage when you type and assign it to a property (text) in state
class MessageForm extends React.Component {
constructor(props) {
super(props)
this.changeHandler = this.changeHandler.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
this.state = {text: ''}
}
handleSubmit(e) {
e.preventDefault();
var message = {
user: this.props.user,
text: this.state.text,
language: this.props.language,
id: 1
}
//Connects to ChatApp component
this.props.onMessageSubmit(message);
//Set the state of the text to empty string so that next inputted text value can be hanled in the state
this.setState({ text: '' })
}
changeHandler(e) {
//change the state of text to inputted value
this.setState({ text: e.target.value });
}
render() {
return (
<div className="message_form">
<h3>Write New Message</h3>
<form onSubmit={this.handleSubmit}>
<input
onChange={this.changeHandler}
value={this.state.text}
placeholder='Write new message'
/>
</form>
</div>
)
}
}
export default MessageForm;
答案 0 :(得分:0)
使用enzyme
和sinon
,您可以执行以下操作:
it("submits message", () => {
// GIVEN
const submitCallback = sinon.spy();
const actualNode = shallow(<MessageForm onMessageSubmit={submitCallback} />);
// WHEN
actualNode.find("input").simulate("change", { target: { value: "Test Message" } });
actualNode.find("form").simulate("submit");
// THEN
sinon.assert.calledWith(submitCallback, "Test Message");
});
这只是基本的交互性测试。您还可以创建测试以验证HTML呈现和状态转换。查看enzyme
文档以获取更多信息。