React 测试库 - 在 fireEvent 之后使用“await wait()”

IT技术 arrays reactjs async-await jestjs react-testing-library
2021-05-08 03:36:00

我正在尝试使用测试库在 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');
        
    });
通过测试——为什么这个通过但第一个失败?

// 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');
      })  
    });

1个回答

5 个月后,我回来回答我的问题(自从发布这个问题以来我学到了很多东西,哈哈)......

首先,由于 5 个月后,我想强调最好使用该userEvent库而不是fireEvent如果可能话。

我也不会指出代码中有很多反模式......你应该只在waitFor. 您应该避免使用getByTestId更易于访问的替代方案。

最后,第一个测试失败的原因是你不能使用waitwith getBy*getBy不是异步的,不会等待。这将是更好的解决方案:

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

然后测试将等待nameWrapper元素可用。

第二个测试通过了,因为getBy它包含在 RTL 的异步实用程序中,waitwait现在已弃用,支持waitFor)。这基本上就是findBy幕后的工作——findBygetBy.

当我发布这个问题时,我并没有完全理解这await是一个 Javascript 关键字(并且只是让代码等待解决的Promise的语法糖)。wait(now waitFor) 是来自 RTL 的实用程序,它将使测试的执行等待直到回调没有抛出错误。