如何使用fetch测试api调用

时间:2017-07-03 20:50:42

标签: javascript unit-testing reactjs mocking fetch

我无法找到关于单位测试fetch在线的正确方法的确切答案。我正在使用create-react-app版本。到目前为止,这是我发现最接近用户建议使用nock& node-fetch。我在这里看到了一些库的开发:https://github.com/wheresrhys/fetch-mock但它的构建失败让我感到紧张。

目标是使用jest

很好地发挥这个作用

有没有人对使用fetch api测试请求的最佳方法有经验建议?

1 个答案:

答案 0 :(得分:2)

您应该使用与您链接的fetch-mock来测试新的fetch api调用。

构建失败的事实对您来说绝对没有任何意义。这只是让开发人员知道何时提交github进行持续开发。当您使用npm i --save-dev fetch-mock时,它将下载github作者专门发布的(希望)工作版本,而不是失败的版本。

我的项目中有关redux thunk动作的示例:

import expect from 'expect';
import configureStore from 'redux-mock-store';
import thunk from 'redux-thunk';
import fetchMock from 'fetch-mock';

import * as actions from './formActions';

const mockStore = configureStore([thunk]);
const store = mockStore({});
const body = {
  email: 'test@gmail.com',
};

describe('registerFormActions', () => {
  let calledActions;

  beforeEach(() => {
    store.clearActions();
    calledActions = store.getActions();
  });

  afterEach(() => {
    fetchMock.reset().restore();
  });

  it('should post form', () => {
    fetchMock.postOnce('/account/register', body);

    store.dispatch(actions.submit()).then(() => {
      expect(fetchMock.called('/account/register')).toBe(true);
    });
  });
});

export const submit = formData => dispatch =>
fetch('/account/register', {
  method: 'post',
  body: formData,
  credentials: 'same-origin',
}).then((response) => {
  if (response.ok) {
     // Do something cool
  }
});