【问题标题】:Wait for fetch() to resolve using Jest for React test?等待 fetch() 解决使用 Jest 进行 React 测试?
【发布时间】:2018-08-06 00:35:15
【问题描述】:

在我的componentDidMountReact.Component 实例中,我有一个fetch() 调用,响应调用setState

我可以模拟请求并使用 sinon 进行响应,但我不知道 fetch 何时会解决它的承诺链。

componentDidMount() {
  fetch(new Request('/blah'))
    .then((response) => {
      setState(() => {
        return newState;
      };
    });
}

在我使用jestenzyme 的测试中:

it('has new behaviour from result of set state', () => {
  let component = mount(<Component />);

  requests.pop().respond(200);

  component.update() // fetch() has not responded yet and
                     // thus setState has not been called yet
                     // so does nothing

  assertNewBehaviour(); // fails

  // now setState occurs after fetch() responds sometime after
});

我是否需要刷新 Promise 队列/回调队列或类似的东西?我可以通过超时重复检查 newBehaviour,但这并不理想。

【问题讨论】:

  • 你在单元测试期间是否在进行实际的 api 调用来获取数据?
  • 不,如问题中所述,我使用 Sinon.js 将其存根。

标签: javascript reactjs unit-testing jestjs enzyme


【解决方案1】:

似乎最好的答案是使用container pattern 并从具有分离关注点的容器类中传递 API 数据并分别测试组件。这允许被测组件简单地将 API 数据作为 props 并使其更易于测试。

【讨论】:

    【解决方案2】:

    由于您没有进行任何真正的 api 调用或其他耗时的操作,因此异步操作将在可预见的短时间内解决。

    因此,您可以稍等片刻。

    it('has new behaviour from result of set state', (done) => {
      let component = mount(<Component />);
      requests.pop().respond(200);
    
      setTimeout(() => {
        try {
          component.update();
          assertNewBehaviour();
          done();
        } catch (error) {
          done(error);
        }
      }, 1000);
    });
    

    【讨论】:

      猜你喜欢
      • 2018-01-29
      • 1970-01-01
      • 2023-03-08
      • 2018-09-07
      • 2019-02-24
      • 2017-09-14
      • 2022-01-26
      • 2019-05-07
      相关资源
      最近更新 更多