使用Jest和React测试库测试Apollo React挂钩

时间:2019-11-29 03:59:34

标签: javascript reactjs jestjs react-apollo react-testing-library

我有一个使用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

我试图确保在用户填写表格并单击提交按钮时调用登录突变。

测试有时会成功运行,而其他时候则失败。我怀疑在运行Expect块之前,未解决loginMutation承诺。

控制台也有以下警告:

  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 */

这是测试:

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)
  })
})

在运行断言之前,如何确保loginMutation承诺已得到解决?

1 个答案:

答案 0 :(得分:0)

请为async act wait签出我的GitHub https://github.com/Arit143/mytube-ui/blob/master/src/pages/List.spec.tsx。通常,我包装动作并在一个函数中等待,然后等待它完成。如果您认为登录解析需要花费很多时间,则可以增加wait的数量。请以GitHub URL为例,以防万一您仍然遇到问题。