【问题标题】:Testing async `componentDidMount()` with Jest + react-testing-library使用 Jest + react-testing-library 测试异步 `componentDidMount()`
【发布时间】:2020-01-20 00:34:02
【问题描述】:

我有一个组件在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() 语句总是失败。

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

This similar questionthis gist snippet 都展示了我如何使用 Enzyme 进行测试。本质上,他们依靠async/await 手动调用componentDidMount()

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

谢谢!

【问题讨论】:

    标签: javascript reactjs jestjs react-testing-library


    【解决方案1】:

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

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

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

    【讨论】:

    • 不确定我理解你的意思,findByText 是异步的,你可以看到它here
    • 哦,我很确定它不是。对不起。
    猜你喜欢
    • 1970-01-01
    • 2021-02-11
    • 1970-01-01
    • 2020-03-22
    • 2020-05-14
    • 2021-02-28
    • 2019-07-08
    • 1970-01-01
    相关资源
    最近更新 更多