gpt4 book ai didi

arrays - React 测试库 - 在 fireEvent 之后使用 'await wait()'

转载 作者:行者123 更新时间:2023-12-03 18:39:53 24 4
gpt4 key购买 nike

我正在尝试使用测试库在 fireEvent.click 之后检查 DOM 元素。我知道我需要在 fireEvent 之后等待,但不知道为什么简单地使用 await 不起作用?下面是用两种方式编写的相同测试——第一个失败,第二个通过。我不明白为什么第一个失败......非常感谢任何见解!
附言-- 我知道 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');

});

通过测试——为什么这个通过但第一个失败?

// 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 以支持更易于访问的替代方案。
最后,第一个测试失败的原因是您不能将 waitgetBy* 一起使用。 getBy 不是异步的,不会等待。这本来是更好的解决方案:

fireEvent.click(button);
const nameWrapper = await findByTestId('name_wrapper');

然后测试将等待 nameWrapper 元素可用。
第二个测试通过了,因为 getBy 包含在 RTL 的异步实用程序 wait 中(现在不推荐使用 wait 以支持 waitFor )。这本质上是 findBy 在幕后所做的 - findBygetBy 的异步版本。
当我发布这个问题时,我并不完全理解 await 是一个 Javascript 关键字(并且只是语法糖,使代码等待解决的 promise )。 wait(现在是 waitFor )是来自 RTL 的一个实用程序,它将使测试的执行等待直到回调没有抛出错误。

关于arrays - React 测试库 - 在 fireEvent 之后使用 'await wait()',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63062395/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com