使用实习生在 React / javascript 中对 http 方法(get,post)进行单元测试

Unit testing http methods (get, post) in react / javascript using intern

这是我第一次编写单元测试 - 请多多关照。

我正在尝试为两个函数编写单元测试。一个功能是 GET 来自 api 的数字,另一个是 POST 数据。

我不知道该怎么做。我知道,我想使用实习生 "expect" 调用和 fetch-mock,但其余的我想在 react / javascript 中完成。我用一些数据做了一个模拟响应。

我的问题是:

  1. 如何使用 fetch-mock 将我的预期输出与我的函数输出进行比较
  2. 我的模拟响应数据与 fetch-mock 有何关系?

同样,我以前没有这样做过,我很难理解在线可用的资源(已经研究了 8 个小时以上)所以我正在寻找另一种意见

我以前没用过fetch-mock,有很多方法可以做到这一点,但是模拟的一般过程是设置模拟,做你需要做的,然后撕裂它以 afterafterEach 的形式下降。您实际如何检查您的 GET 请求是否有效取决于您首先如何发出请求。

模拟请求的测试可能看起来像这样。这里的假设是你有一个请求方法,它发出一个请求并且 return 是一个 Promise(如果你做了 return fetch('some_url') 你会得到什么)。

import * as fetchMock from 'fetch-mock';
const { describe, it, afterEach } = intern.getPlugin('interface.bdd');
const { expect } = intern.getPlugin('chai');

describe('my suite', () => {
  afterEach(() => {
    fetchMock.restore();
  });

  it('should do something', () => {
    fetchMock.get('*', { hello: 'world' });
    return thingThatDoesAGetRequest.then(response => {
      expect(response).to.equal({ hello: 'world' });
    });
  })
});

另一种选择是等待模拟请求完成,而不是查看函数 return 值:

it('should do something', test => {
  // Create a promise that will resolve when a request is made
  const promise = new Promise(resolve => {
    fetchMock.get('*', () => {
      resolve();
      return { hello: 'world' }
    });
  });

  // Do whatever should be making a call
  thingThatDoesAGetRequest();

  // Wait for the request promise to resolve, then see if whatever
  // you expect to happen has happened
  return promise.then(() => {
    expect(something).to.equal({ hello: 'world' });
  });
})