我想用Jest和Enzyme测试一个React组件.此组件是一个登录表单,当用户单击登录按钮时,我想根据结果检查对象模型是否相应地更新了对象模型.
以下是用户单击提交按钮时调用的代码部分.
// Login.jsx
handleSubmit(e) {
var that = this;
this.setState({stateResult: "", errorLabel: ""});
if(e) {
e.preventDefault();
e.stopPropagation();
}
MyService.login(this.state.email, this.state.password).then(function(account) {
that.setState({stateResult: "login-ok", errorLabel: ""});
}).catch(function(err) {
that.setState({stateResult: "login-error", errorLabel: err.data.message});
});
};
Run Code Online (Sandbox Code Playgroud)
我写了一个Jest测试.这是代码:
// Login-test.js
test('that when the signin fails, the stateResult model is updated with login-error', () => {
const wrapper = shallow(<Landing />);
wrapper.find('a#landingjsx-signin').simulate('click');
wrapper.update();
setTimeout(function() {
expect(wrapper.state().stateResult).toEqual("login-error");
}, 100);
});
Run Code Online (Sandbox Code Playgroud)
为了测试它,我使用MyService的模拟
jest.mock('../../../modules/MyService.js');
Run Code Online (Sandbox Code Playgroud)
这是我的模拟代码:
//MyService.js
class MyService {
constructor() {
}
login(user, password) {
return new …Run Code Online (Sandbox Code Playgroud)