![](/img/trans.png)
[英]How to use react-hooks with Jest and react-testing-library
[英]Testing Apollo React Hooks with Jest & 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
我試圖確保在用戶填寫表單並單擊提交按鈕時調用登錄突變。
測試有時會成功運行,有時會失敗。 我懷疑 loginMutation 承諾在運行 expect 塊之前沒有得到解決。
控制台還有以下警告:
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 for async act wait
。 通常,我將行為包裝起來並在函數中等待,然后等待它完成。 如果您覺得登錄解析需要很長時間,您可以增加wait
時間。 以 GitHub URL 為例,如果您仍然遇到問題,請告訴我。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.