用Jest + react-testing-library测试异步`componentDidMount()` [英] Testing async `componentDidMount()` with Jest + react-testing-library

查看:167
本文介绍了用Jest + react-testing-library测试异步`componentDidMount()`的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个组件可以在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();
});

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

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.

类似的问题此要点摘录都说明了如何使用酶进行测试.本质上,他们依靠async/await手动调用componentDidMount().

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.

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

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.

谢谢!

推荐答案

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

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.

这篇关于用Jest + react-testing-library测试异步`componentDidMount()`的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆