如何测试异步handleSubmit(e)与jest和酶的反应

时间:2018-04-05 13:37:05

标签: reactjs enzyme jest

我想测试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上使用。

1 个答案:

答案 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');
});