Login
handleLoginSubmit
提交表单时调用的方法。这个方法实际上是在我的
store
登录
handleLoginSubmit = async (event) => {
event.preventDefault();
const result = await service.validateUser(this.username, this.password);
if (result) {
this.isAuthenticated = true;
this.invalidLogin = false;
history.push('/search');
}
else this.invalidLogin = true;
}
我已经编写了测试用例来检查
handleSubmit
提交表单时,以及验证是否正确:
describe('Login should authenticate users corectly when', () => {
it('correct credentials are submitted', async () => {
const spySubmit = jest.spyOn(store, 'handleLoginSubmit');
const spyValidate = jest.spyOn(service, 'validateUser');
const wrapper = shallow(<Login store={store} />);
expect(spySubmit).toHaveBeenCalledTimes(0);
wrapper.find('form').simulate('submit');
expect(spySubmit).toHaveBeenCalledTimes(1);
expect(spyValidate).toBeCalledWith({ username: store.username, password: store.password });
});
});
服务.js:
export function validateUser(username, password) {
return fetch(`https://abc.co/api?search=${username}`)
.then(function (response) {
return response.json();
}).then(function (response) {
if (response.results.length) {
if (response.results[0].key === password) {
return true;
}
else return false;
}
else return false;
});
}
service.validateUser
即使没有,也不会被调用
登录