如何使用模拟 api 调用测试 React 组件

How to test react component with mock api calls

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

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

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

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

使用 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
  });
});