【发布时间】:2020-11-13 15:50:22
【问题描述】:
我正在尝试使用测试库在 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');
})
});
【问题讨论】:
-
在第一个示例中,
getByTestId没有返回 Promise,因此这些等待毫无意义。 -
在第二个例子中你可以做
await wait()然后继续。 -
您可以在testing-library.com/docs/dom-testing-library/api-async 上阅读更多内容,这里有一些很好的例子。例如。
await waitFor(callback)所做的是等待回调为真,然后继续。 -
不,但你可以先
await waitFor(() => getByTestId(...)); const el = getByTestId(...)。 -
另一个好的来源是jestjs.io/docs/en/asynchronous
标签: arrays reactjs async-await jestjs react-testing-library