繁体   English   中英

编写前端组件的Mocha测试规范(react.js)

[英]Writing Mocha Test Specs for front end component (react.js)

在为前端组件编写摩卡测试规格时,我遇到了很多麻烦。 我的组件看起来非常简单,但是却不知道如何编写测试规范。 有人可以帮我吗? 任何帮助将不胜感激! 谢谢

 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; 

使用enzymesinon您可以执行以下操作:

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文档以获得更多信息。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM