我想测试jest
中提交表单的情况
表单onSubmit
链接到handleSubmit(e)
,这是async
方法(它会检查用户名是否已被使用)。
有谁知道我如何测试onSubmit?
Register.js
class AddItems extends Component {
async checkForErrors() {
...
const usernameValid = await this.checkIfUsernameIsValid(this.state.username);
...
async handleSubmit(e) {
e.preventDefault();
const err = await this.checkForErrors();
...
render() {
...
<Form onSubmit={this.handleSubmit.bind(this)}>
Register.test.js
fetch.mockResponse(JSON.Stringify({result: true}); //username is valid
//fill in the form-fields
form.simulate('submit');
expect(fetch.mock.calls[1]).toContainEqual('/users/register');
fetch.mock
只有1个电话;至/users/validUsername
我知道如果onSubmit
本身没有onSubmit
,您可以在jest中使用await,但不能在async
上使用。
答案 0 :(得分:2)
你试过这些吗?
(从https://facebook.github.io/jest/docs/en/asynchronous.html复制)
test('the data is peanut butter', async () => {
expect.assertions(1);
await expect(fetchData()).resolves.toBe('peanut butter');
});
test('the fetch fails with an error', async () => {
expect.assertions(1);
await expect(fetchData()).rejects.toMatch('error');
});