Jos*_*man 7 forms testing reactjs react-testing-library
我有一个表格,在处理时显示“正在提交”状态,在完成后显示“已提交”状态。
这是我正在使用的提交处理程序......
const handleSubmit = (e, _setTitle) => {
e.preventDefault()
_setTitle('Submitting...')
try {
doformStuff(emailRef.current.value)
} catch (err) {
throw new Error(err)
} finally {
_setTitle('Submitted perfectly.')
}
}
Run Code Online (Sandbox Code Playgroud)
我想测试提交状态是否出现,无论多短。
it('shows "submitting" when submitting', async () => {
// arrange
render(<MobileEmailCapture/>)
// act
const emailInput = screen.getByPlaceholderText('yourem@il.com')
userEvent.type(emailInput, fakeEmail)
fireEvent.submit(screen.getByTestId('form'))
// assert
expect(screen.getByTestId('title')).toHaveTextContent('Submitting...')
})
Run Code Online (Sandbox Code Playgroud)
问题是测试直接跳转到提交状态
Error: FAILED Expected 'Submitted perfectly.' to match 'Submitting...'.
我知道这就是最终的结果,但我想测试临时过渡状态。我怎么做?
问题是screen.getByTestId('title')在测试生命周期中可能会保存多个值。对我有用的一种方法是waitFor精确的瞬态值。像这样的东西应该适用于您的示例:
async screen.findByText('Submitting...');
Run Code Online (Sandbox Code Playgroud)
老实说,我不确定这是否是解决这个问题的“正确”方法。我自己对这项技术还很陌生。据我了解,findByText 正在使用 polling,所以我怀疑这种方法可能会导致不稳定的结果。但这对我有用。