使用 Jest + react-testing-library 测试异步 `componentDidMount()`

IT技术 javascript reactjs jestjs react-testing-library
2021-05-14 15:32:35

我有一个组件可以异步获取数据 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({ .... });
    })
  ;
}

我对组件的测试如下所示 -

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();
});

由于渲染和加载数据是异步的,我的expect()语句会继续执行componentDidMount()并在假异步调用完成执行之前执行,因此expect()语句总是失败。

我想我可以引入某种延迟,但这感觉不对,当然会增加我的测试运行时间。

这个类似的问题这个要点片段都展示了我如何用酶测试这个。本质上,他们依靠async/手动await调用componentDidMount()

但是react-testing-library似乎不允许直接访问组件以直接调用其方法(可能是设计使然)。所以我不确定要等待的“什么”,或者这是否是正确的方法。

谢谢!

1个回答

这取决于您的组件在做什么。想象一下,您的组件显示一条加载消息,然后显示一条欢迎消息。您将等待欢迎消息出现:

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

考虑它的最好方法是打开浏览器查看您的组件。什么时候知道它是装的?尝试在您的测试中重现它。