[英]Test Drop Down With React Testing Library
I am having trouble testing a drop down populated with data from an API call in React Testing Library.我在测试包含来自 React 测试库中 API 调用的数据的下拉列表时遇到问题。 Below is a CodeSandbox showing the issue
下面是一个显示问题的 CodeSandbox
https://codesandbox.io/s/mutable-sea-wtt9u https://codesandbox.io/s/mutable-sea-wtt9u
If I change App
to use a hardcoded array to populate the drop down (commented out in App
component), the test passes.如果我将
App
更改为使用硬编码数组来填充下拉列表(在App
组件中注释掉),则测试通过。
Thanks谢谢
When your data comes from an asynchronous fetch call, the DOM doesn't get updated synchronously, and you have to use one of the async utilities to wait for the update.当您的数据来自异步获取调用时,DOM 不会同步更新,您必须使用异步实用程序之一来等待更新。 This works in your case (tested in your Codesandbox):
这适用于您的情况(在您的 Codesandbox 中测试):
// import `wait` directly from React Testing Library
import { render, wait } from '@testing-library/react';
...
await wait(() => {
fireEvent.change(selectElement, { target: { value: "1" } });
expect(selectElement.value).toBe("1");
});
Here's the React Testing Library docs on async utilities: https://testing-library.com/docs/dom-testing-library/api-async这是有关异步实用程序的 React 测试库文档: https : //testing-library.com/docs/dom-testing-library/api-async
EDIT: It looks like you might have changed your CodeSandbox code.编辑:看起来您可能已经更改了 CodeSandbox 代码。 Now you need to wait for the async call to be made before firing the event, since you're fetching data on mount.
现在您需要等待异步调用在触发事件之前进行,因为您正在获取挂载数据。 I've updated my answer and made sure tests pass on your current CodeSandbox.
我已经更新了我的答案并确保测试通过您当前的 CodeSandbox。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.