简体   繁体   中英

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. Below is a CodeSandbox showing the issue

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.

Thanks

You need to mock your fetch events. 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. This works in your case (tested in your 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

EDIT: It looks like you might have changed your CodeSandbox code. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM