简体   繁体   English

使用 Jest 和 React 测试库测试 Apollo React Hooks

[英]Testing Apollo React Hooks with Jest & React Testing Library

I have a form that uses an Apollo mutation hook:我有一个使用 Apollo 突变挂钩的表单:

import React from 'react'
import { useFormik } from 'formik'
import { useLoginMutation } from '../generated'

const LoginContainer = () => {
  const [loginMutation, { data, loading, error }] = useLoginMutation()

  const formik = useFormik({
    initialValues: {
      email: '',
      password: '',
    },
    onSubmit: values => {
      loginMutation({
        variables: {
          input: {
            email: String(values.email).trim(),
            password: values.password,
          },
        },
      })
    },
  })

  return (
    <form
      onSubmit={event => {
        event.preventDefault()
        formik.handleSubmit(event)
      }}
    >
      <input
        data-testid="login-email-input"
        name="email"
        placeholder="Email address"
        //  label="Email"
        required
        type="email"
        value={formik.values.email}
        onChange={formik.handleChange}
      />
      <input
        data-testid="login-password-input"
        name="password"
        placeholder="password"
        //  label="Password"
        required
        type="password"
        value={formik.values.password}
        onChange={formik.handleChange}
      />
      <button data-testid="login-submit-input" type="submit">
        LOGIN
      </button>
    </form>
  )
}

export default LoginContainer

I am trying to make sure the login mutation is called when the user fills in the form and clicks the submit button.我试图确保在用户填写表单并单击提交按钮时调用登录突变。

The test runs successfully sometimes and fails other times.测试有时会成功运行,有时会失败。 I suspect that the loginMutation promise is not being resolved before the expect block is run.我怀疑 loginMutation 承诺在运行 expect 块之前没有得到解决。

The console also has the following warning:控制台还有以下警告:

  Warning: An update to LoginContainer inside a test was not wrapped in act(...).

    When testing, code that causes React state updates should be wrapped into act(...):

    act(() => {
      /* fire events that update state */
    });
    /* assert on the output */

Here is the test:这是测试:

describe('login container', () => {
  let loginMutationCalled = false

  const variables = {
    input: {
      email: 'test@example.com',
      password: '123',
    },
  }

  const result = () => {
    loginMutationCalled = true
    return {
      data: {
        Login: {
          accountId: '123',
        },
      },
    }
  }

  const mocks = [
    {
      request: {
        query: LOGIN_MUTATION,
        variables,
      },
      result,
    },
  ]

  it('should call the login mutation', async () => {
    await act(async () => {
      const { findByTestId } = render(
        <MockedProvider mocks={mocks} addTypename={false}>
          <LoginContainer />
        </MockedProvider>,
      )

      fireEvent.change(await findByTestId('login-email-input'), {
        target: {
          value: 'test@example.com',
        },
      })

      fireEvent.change(await findByTestId('login-password-input'), {
        target: {
          value: '123',
        },
      })

      await wait(async () =>
        fireEvent.click(await findByTestId('login-submit-input')),
      )
    })

    expect(loginMutationCalled).toBe(true)
  })
})

How do I make sure the loginMutation promise has been resolved before running the assertions?在运行断言之前,如何确保已解决 loginMutation 承诺?

Please check out my GitHub https://github.com/Arit143/mytube-ui/blob/master/src/pages/List.spec.tsx for async act wait .请查看我的 GitHub https://github.com/Arit143/mytube-ui/blob/master/src/pages/List.spec.tsx for async act wait Usually, I wrap the act and wait in a function and then just wait for it to fulfill.通常,我将行为包装起来并在函数中等待,然后等待它完成。 If you feel the login resolve is taking much time, you can increase the wait amount.如果您觉得登录解析需要很长时间,您可以增加wait时间。 Just have a look at the GitHub URL as an example and let me know in case you still face an issue.以 GitHub URL 为例,如果您仍然遇到问题,请告诉我。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM