javascript - 使用 Jest 和 React 测试库测试 Apollo React Hooks
问题描述
我有一个使用 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
我试图确保在用户填写表单并单击提交按钮时调用登录突变。
测试有时会成功运行,有时会失败。我怀疑 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 承诺已得到解决?
解决方案
请查看我的 GitHub https://github.com/Arit143/mytube-ui/blob/master/src/pages/List.spec.tsx以获取async act wait
. 通常,我将行为包装起来并在一个函数中等待,然后等待它完成。如果您觉得登录解析花费了很多时间,您可以增加wait
数量。以 GitHub URL 为例,如果您仍然遇到问题,请告诉我。
推荐阅读
- java - 从枚举到文本文件中的动态值
- android - Firebase 测试实验室和 Google 发布前报告 Google 登录失败/普通用户不受影响
- c# - 使用参数的带有 restSharp 的 HTTP 获取请求
- java - 用java涂鸦(鼠标监听器)
- python - FileNotFoundError:[Errno 2] 没有这样的文件或目录:'fluidsynth':'fluidsynth'
- algorithm - 多项式函数的复杂度是什么意思?
- java - 有人还在用Java吗?请问这个可以翻译吗?
- extjs - 如何从按钮单击重定向到另一个视图(ExtJS 6.2)
- javascript - 如何检查变量是否未定义与在javascript中未声明?
- ios - 以编程方式制作圆形按钮