2017-02-13 65 views
0

我在爲我的前端組件編寫摩卡測試規格時遇到了很多麻煩。 我的組件看起來非常簡單,但只是不知道如何編寫測試規範。 有人可以幫助我嗎? 任何幫助將不勝感激! 感謝爲前端組件寫作摩卡測試規格(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 { 
 
\t constructor(props) { 
 
\t \t super(props) 
 
\t \t this.changeHandler = this.changeHandler.bind(this); 
 
\t \t this.handleSubmit = this.handleSubmit.bind(this); 
 
\t \t this.state = {text: ''} 
 
\t } 
 

 
\t handleSubmit(e) { 
 
\t \t e.preventDefault(); 
 
\t \t var message = { 
 
\t \t \t user: this.props.user, 
 
\t \t \t text: this.state.text, 
 
\t \t \t language: this.props.language, 
 
\t \t \t id: 1 
 
\t \t } 
 
\t \t //Connects to ChatApp component 
 
\t \t this.props.onMessageSubmit(message); 
 
\t \t //Set the state of the text to empty string so that next inputted text value can be hanled in the state 
 
\t \t this.setState({ text: '' }) 
 
\t } 
 

 
\t changeHandler(e) { 
 
\t \t //change the state of text to inputted value 
 
\t \t this.setState({ text: e.target.value }); 
 
\t } 
 

 
\t render() { 
 
\t \t return (
 
\t \t \t <div className="message_form"> 
 
\t \t \t \t <h3>Write New Message</h3> 
 
\t \t \t \t <form onSubmit={this.handleSubmit}> 
 
\t \t \t \t \t <input 
 
\t \t \t \t \t \t onChange={this.changeHandler} 
 
\t \t \t \t \t \t value={this.state.text} 
 
\t \t \t \t \t \t placeholder='Write new message' 
 
\t \t \t \t \t /> 
 
\t \t \t \t </form> 
 
\t \t \t </div> 
 
\t \t) 
 
\t } 
 
} 
 

 
export default MessageForm;

+0

這將是很好的提供提交按鈕。 – luboskrnac

回答

0

隨着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文檔以獲取更多信息。