Testing async `componentDidMount()` with Jest + react-testing-library

耗尽温柔 提交于 2020-05-15 10:05:23

问题


I have a component that fetches data asynchronously in componentDidMount()

componentDidMount() {
  const self = this;

  const url = "/some/path";
  const data = {}
  const config = {
    headers: { "Content-Type": "application/json", "Accept": "application/json" }
  };

  axios.get(url, data, config)
    .then(function(response) {
      // Do success stuff

      self.setState({ .... });
    })
    .catch(function(error) {
      // Do failure stuff

      self.setState({ .... });
    })
  ;
}

My test for the component looks like this -

it("renders the component correctly", async () => {
  // Have API return some random data;
  let data = { some: { random: ["data to be returned"] } };
  axios.get.mockResolvedValue({ data: data });

  const rendered = render(<MyComponent />);
  // Not sure what I should be awaiting here
  await ???

  // Test that certain elements render
  const toggleContainer = rendered.getByTestId("some-test-id");
  expect(toggleContainer).not.toBeNull();
});

Since rendering and loading data is async, my expect() statements go ahead and execute before componentDidMount() and the fake async call finish executing, so the expect() statements always fail.

I guess I could introduce some sort of delay, but that feels wrong and of course increases my runtime of my tests.

This similar question and this gist snippet both show how I can test this with Enzyme. Essentially they rely on async/await to call componentDidMount() manually.

However react-testing-library doesn't seem to allow direct access to the component to call its methods directly (probably by design). So I'm not sure "what" to wait on, or whether that's even the right approach.

Thanks!


回答1:


It depends on what your component is doing. Imagine your component shows a loading message and then a welcome message. You would wait for the welcome message to appear:

const { getByText, findByText } = render(<MyComponent />)
expect(getByText('Loading...')).toBeInTheDocument()
expect(await findByText('Welcome back!')).toBeInTheDocument()

The best way to think about it is to open the browser to look at your component. When do you know that it is loaded? Try to reproduce that in your test.



来源:https://stackoverflow.com/questions/58003144/testing-async-componentdidmount-with-jest-react-testing-library

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!