Lyd*_*iks 10 arrays async-await reactjs jestjs react-testing-library
我正在尝试使用测试库在 fireEvent.click 之后检查 DOM 元素。我知道我需要在 fireEvent 之后等待,但不知道为什么简单地使用 await 不起作用?下面是用两种方式编写的相同测试——第一个失败,第二个通过。我不明白为什么第一个失败......非常感谢任何见解!
ps——我知道wait已被弃用,waitFor是首选,但是由于一些限制,我目前无法更新版本:(
失败的测试
// This test fails with the following error and warning:
// Error: Unable to find an element by: [data-test="name_wrapper"]
// Warning: An update to OnlinePaymentModule inside a test was not wrapped in act(...).
it('this is a failing test...why', async () => {
const { getByText, getByTestId } = render(<Modal {...props} />);
const button = getByText('open modal');
fireEvent.click(button);
const nameWrapper = await getByTestId('name_wrapper');
expect(
nameWrapper.getElementsByTagName('output')[0].textContent
).toBe('Jon Doe');
const numberWrapper = await getByTestId('number_wrapper');
expect(
numberWrapper.getElementsByTagName('output')[0].textContent
).toBe('123456');
});Run Code Online (Sandbox Code Playgroud)
// This test passes with no warnings
it('this is a passing test...why', async () => {
const { getByText, getByTestId } = render(<Modal {...props} />);
const button = getByText('open modal');
fireEvent.click(button);
await wait(() => {
const nameWrapper = getByTestId('name_wrapper');
expect(
nameWrapper.getElementsByTagName('output')[0].textContent
).toBe('Jon Doe');
const numberWrapper = getByTestId('number_wrapper');
expect(
numberWrapper.getElementsByTagName('output')[0].textContent
).toBe('123456');
})
});Run Code Online (Sandbox Code Playgroud)
Lyd*_*iks 24
5 个月后,我回来回答我的问题(自从发布这个问题以来,我学到了很多东西,哈哈)......
首先,由于 5 个月后,我想强调最好使用该userEvent库,而不是fireEvent如果可能的话。
我也不会指出代码中有很多反模式......你应该只在waitFor. 您应该避免使用getByTestId更容易获得的替代品。
最后,第一个测试失败的原因是你不能使用waitwith getBy*。getBy不是异步的,不会等待。这本来是更好的解决方案:
fireEvent.click(button);
const nameWrapper = await findByTestId('name_wrapper');
Run Code Online (Sandbox Code Playgroud)
然后测试将等待nameWrapper元素可用。
第二个测试通过,因为getBy它包含在 RTL 的 async 实用程序中,wait(wait现在已弃用,支持waitFor)。这基本上就是findBy幕后的工作——findBy是getBy.
当我发布这个问题时,我没有完全理解这await是一个 Javascript 关键字(只是语法糖,使代码等待解决的承诺)。wait(now waitFor) 是来自 RTL 的一个实用程序,它将使测试的执行等待直到回调没有抛出错误。
| 归档时间: |
|
| 查看次数: |
12202 次 |
| 最近记录: |