如何测试我的 node/express 应用程序正在进行 API 调用(通过 axios)

How to test my node/express app is making an API call (through axios)

当用户访问我的应用程序主页时,我的 express 后端向外部 API 发出 RESTful http 请求,即 returns 一个 JSON。

我想测试我的应用程序是否正在进行 API 调用(实际上并未进行)。我目前正在使用 Chai 在 Mocha 中进行测试,并且一直在使用 Sinon 和 Supertest。

describe('Server path /', () => {
  describe('GET', () => {
    it('makes a call to API', async () => {
      // request is through Supertest, which makes the http request
      const response = await request(app)
        .get('/')

      // not sure how to test expect axios to have made an http request to the external API
    });
  });
});

我不关心服务器给出的响应,我只想检查我的应用程序是否使用正确的路径和 headers(使用 api 键等进行调用)。 .)

也许您可以尝试检查从 API 的响应中返回的代码。但基本上要检查代码是否执行 API 调用,您必须这样做。

我过去针对这种情况所做的是使用 Sinon 对服务器调用进行存根。假设您有一个服务器调用方法

// server.js
export function getDataFromServer() {
  // call server and return promise
}

在测试文件中

const sinon = require('Sinon');
const server = require('server.js'); // your server call file

describe('Server path /', () => {  
  before(() => { 
    const fakeResponse = [];
    sinon.stub(server, 'getDataFromServer').resolves(fakeResponse); // I assume your server call is promise func
  });

  after(() => {
    sinon.restore();
  });

  describe('GET', () => {
    it('makes a call to API', async () => {
      // request is through Supertest, which makes the http request
      const response = await request(app)
        .get('/')
      ...   
    });
  });
});

希望能给您带来启发。