如何使用 fetch 测试 api 调用

How to test api calls using fetch

我无法在网上找到关于单元测试 fetch 的正确方法的明确答案。我正在使用 create-react-app 版本。到目前为止,这是我发现的最接近用户推荐使用 nock & node-fetch 的地方。我在这里看到了图书馆的一些发展:https://github.com/wheresrhys/fetch-mock 但它的构建失败了,这让我很紧张。

目标是让这部剧与jest

有没有人根据经验对使用提取测试请求的最佳方法提出任何建议api?

您应该像链接一样使用 fetch-mock 来测试新的提取 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
  }
});