【问题标题】:How to test api calls using fetch如何使用 fetch 测试 api 调用
【发布时间】:2017-07-03 20:50:41
【问题描述】:

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

我们的目标是与jest 配合得很好

对于使用 fetch api 测试请求的最佳方式,是否有人有任何经验建议?

【问题讨论】:

    标签: javascript unit-testing reactjs mocking fetch


    【解决方案1】:

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

    【讨论】:

    • 嗯,很高兴听到其他使用过它的人的消息。我会继续前进。谢谢,害怕掉进兔子洞。
    • 没问题。下次我只是看看文档,如果它看起来像你需要的,那么没有理由不使用它,特别是对于不是生产代码的单元测试。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-24
    • 2018-04-13
    • 2019-08-25
    • 1970-01-01
    • 2021-06-15
    • 2018-10-24
    相关资源
    最近更新 更多