简体   繁体   English

使用 React 测试库进行测试下拉

[英]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谢谢

You need to mock your fetch events.您需要模拟您的 fetch 事件。 I wrote an article on how to do that.我写了一篇关于如何做到这一点的文章。 You can find it here .你可以在 这里找到它。

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.

相关问题 如何使用 react-testing-library 和 framer-motion 测试 mousemove 拖放 - How to test mousemove drag and drop with react-testing-library and framer-motion 如何使用 react-testing-library 测试材质 ui MenuList 组件上的按键按下事件 - How to test key down event on material ui MenuList component using react-testing-library 当没有使用测试库 react 和 jest 传递给它的道具时,将调用按钮的测试 onClick - Test onClick of a button is called when there is no props passed down to it using testing library react and jest React 测试库:测试属性/道具 - React testing library: Test attribute / prop 用React测试库测试文档对象 - Test with react testing library the document object 如何使用 React 测试库测试 `contenteditable` 事件 - How to test `contenteditable` events with React Testing Library 带有 React 测试库的测试输入搜索框 - Test input Search box with React testing library 如何测试使用 React 测试库检查的复选框? - How to test checkbox checked with React Testing Library? 如何使用反应测试库测试 HOC - How to test HOC using react testing library Axios 单元测试与 React 测试库和 typescript - Axios unit test with React testing library and typescript
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM