Joe*_*dee 4 javascript unit-testing reactjs
我有以下React组件:
export default class SignUpForm extends React.Component {
...
doSignupForm(event) {
// Some API call...
}
render() {
return (
<div>
<form action="/" onSubmit={this.doSignupForm.bind(this)} id="register-form">
<button type="submit" id="register_button">Sign Up</button>
</form>
</div>
);
}
};
Run Code Online (Sandbox Code Playgroud)
我想测试该按钮是否触发了该doSignupForm功能 - 我该怎么做(理想情况下使用Mocha/Chai/Enzyme/Sinon)?
此外,正如您所看到的,该doSignupForm函数会触发API调用 - 应该使用集成测试(?)单独测试此API调用.
您可以使用React Utils模拟表单提交:
var rendered = TestUtils.renderIntoDocument(SignupForm);
var form = TestUtils.findRenderedDOMComponentWithTag(rendered, 'form');
TestUtils.Simulate.submit(form);
Run Code Online (Sandbox Code Playgroud)
此外,测试对实际API的调用是不可靠的,您应该使用您期望的响应来模拟API调用,一个想法是将API调用提取到其自己的模块中,并设置间谍来测试您的行为.具有特定响应的组件(使用Jasmine的示例间谍):
spyOn(apiModule, "requestProjects").and.callFake(function() {
return { ...someProjects };
});
Run Code Online (Sandbox Code Playgroud)
参考:
https://facebook.github.io/react/docs/test-utils.html https://volaresystems.com/blog/post/2014/12/10/Mocking-calls-with-Jasmine
如此处所述,Enzyme 不支持事件冒泡。因此,找到了以下解决方法:
import sinon from 'sinon';
import {mount} from 'enzyme';
import chai from 'chai';
var expect = chai.expect;
it('fires form submit', () => {
const doSignupForm = sinon.stub(SignUpForm.prototype, 'doSignupForm').returns(true);
const wrapper = mount(<SignUpForm />);
wrapper.find('#register_button').get(0).click();
expect(doSignupForm).to.have.been.called;
doSignupForm.restore();
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5003 次 |
| 最近记录: |