【问题标题】:How to test react component with mock api calls如何使用模拟 api 调用测试反应组件
【发布时间】:2018-08-14 19:42:56
【问题描述】:

我正在尝试为一个 React 组件运行测试;但是,此组件的状态是根据从 API 调用获得的响应设置的。

componentDidMount() {
  getStatus().then(status => {
    this.setState({status: status});
  });
}

有没有办法使用 Mocha 来模拟此响应,而不是实际使用 API?由于这是在componentDidMount() 中,所以我总是会使用 Enzyme 的shallowmount 到达这个块,它会抛出fetch is not defined 错误

我可以通过在我的测试设置文件中导入isomorphic-fetch 来消除此错误,但我更愿意只是模拟一个假的 api 并弥补响应。

【问题讨论】:

    标签: javascript reactjs mocha.js enzyme


    【解决方案1】:

    使用fetch-mock 模拟isomorphic-fetch api 调用。

    var fetchMock = require('fetch-mock');
    
    describe('Test mocking isomorphic-fetch', function() {
      before(function() {
        fetchMock.get('/my/api/endpoint', {hello: 'world'});
      });
    
      after(function() {
        fetchMock.restore();
      });
    
      it('should mock fetch', function() {
        // your test code here
      });
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-19
      • 1970-01-01
      • 1970-01-01
      • 2021-05-02
      • 1970-01-01
      • 2019-11-05
      • 2021-05-25
      • 2019-09-03
      相关资源
      最近更新 更多