1
我正在使用Chai,Sinon和Mocha進行測試。如何使用Sinon和Chai單元測試表單
我正在使用Redux-Forms以及ReactJS。
我想測試點擊忘記密碼頁面上的提交後會發生什麼。
這裏是我到目前爲止的代碼:
反應文件:
propTypes: {
fields: React.PropTypes.object.isRequired,
message: React.PropTypes.string.isRequired,
handleSubmit: React.PropTypes.func.isRequired,
},
renderForm: function() {
const { fields: {email}, handleSubmit, isFetching } = this.props;
const iconClass = "fa fa-star-o";
return(
<form form="forgotPassword" name="forgotPassword" className="stack-input">
<ReduxFormTextInput
{...email}
floatingLabelText="Email Address" />
<div className="clearfix" />
<div className="form-footer">
<ButtonSpinner spinner={isFetching} onClick={handleSubmit} ripple={true} raised={true} primary={true} >
<i className={iconClass} />Send
</ButtonSpinner>
</div>
</form>
);
},
renderMessage: function() {
return(
<div>
<i className="fa fa-exclamation-circle" style={{marginRight: '4px'}}/>
If your email is in the system, then it will be sent.
</div>
);
},
//Checks if user has submitted email.
emailSubmit: function(){
var locus = this, props = locus.props;
if(props.message === ''){
return null;
}
else if(props.message === 'SENT'){
return true;
}
return null;
},
render(){
var locus = this, props= locus.props;
return(
<div className="page-wrap">
<div className="page-column">
<h2>Forgot Your Password</h2>
{this.emailSubmit() ? this.renderMessage(): this.renderForm()}
</div>
</div>
);
}
單元測試文件:
describe('ForgotPasswordForm',() => {
const component = setup({
fields: {
email: {
onChange: spy(),
onBlur: spy(),
onFocus: spy()
}
}, // React.PropTypes.object.isRequired,
message: '', // React.PropTypes.string.isRequired,
handleSubmit: spy() // React.PropTypes.func.isRequired,
//onClearMessage:spy() //, React.PropTypes.func.isRequired
}),
domRoot = TestUtils.findRenderedDOMComponentWithClass(component, 'page-wrap'),
title = TestUtils.findRenderedDOMComponentWithTag(component, 'h2'),
submitButton = TestUtils.findRenderedDOMComponentWithClass(component, 'material-D-button'),
form = TestUtils.findRenderedDOMComponentWithTag(component, 'form'),
inputs = TestUtils.scryRenderedDOMComponentsWithTag(component, 'input'),
emailInput = inputs[0];
這個測試失敗保持,儘管多次嘗試。我沒有使用Spy()的經驗,所以我不確定我是否應該使用calledWith。
it ('should display "If your email is in the system, then it will be sent." on submit',() => {
TestUtils.Simulate.change(emailInput, {target: {value: '[email protected]'}});
TestUtils.Simulate.click(submitButton);
expect(domColumn.text).to.equal("Forgot Your Password");
});
這是我得到的迴應。
+"If your email is in the system, then it will be sent."
- -"Forgot Your PasswordSend"
我使用innerHTML來了解點擊後會出現什麼內容,我不認爲點擊甚至是註冊。
當我嘗試做TestUtils.Simulate.change(emailInput, {target: {value: '[email protected]'}});
時,它不起作用。我必須在組件中填充電子郵件的值。