我正在尝试使用测试库在 fireEvent.click 之后检查 DOM 元素。我知道我需要在 fireEvent 之后等待,但不确定为什么简单地使用 wait 不起作用?下面是以两种方式编写的相同测试——第一个失败,第二个通过。我不明白为什么第一个失败了......非常感谢任何见解!
附注-- 我知道 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');
});
PASSING TEST -- Why does this pass but first one fails?
// 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');
})
});
5个月后我回来回答我的问题(自从发布这个问题以来我学到了很多东西哈哈)......
首先,由于已经过去了 5 个月,我想强调的是,最好使用userEvent
图书馆而不是fireEvent
如果可能的话。
如果我不指出代码中有很多反模式,那也是我的失职……你应该只在以下位置做出一个断言:waitFor
。你应该避免使用getByTestId
赞成更容易获得的替代方案。
最后,第一次测试失败的原因是你不能使用wait
with getBy*
. getBy
不是异步的并且不会等待。这本来是更好的解决方案:
fireEvent.click(button);
const nameWrapper = await findByTestId('name_wrapper');
然后测试会等待nameWrapper
元素可用。
第二次测试通过了,因为getBy
包含在 RTL 的异步实用程序中,wait
(wait
现已弃用,取而代之的是waitFor
)。这本质上就是findBy
在幕后做的——findBy
是异步版本getBy
.
当我发布问题时我并不完全明白await
是一个 Javascript 关键字(只是让代码等待承诺解析的语法糖)。wait
(now waitFor
) 是 RTL 中的一个实用程序,它将使测试的执行等待,直到回调不抛出错误。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)