Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/42.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js 如何测试我的node/express应用程序正在进行API调用(通过axios)_Node.js_Express_Testing_Mocha.js_Chai - Fatal编程技术网

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

Node.js 如何测试我的node/express应用程序正在进行API调用(通过axios),node.js,express,testing,mocha.js,chai,Node.js,Express,Testing,Mocha.js,Chai,当用户访问我的应用程序主页时,我的express后端向外部API发出RESTful http请求,该请求返回JSON 我想测试我的应用程序是否正在进行API调用(而不是实际进行调用)。我目前正在摩卡和Chai一起测试,并一直在使用Sinon和Supertest describe('Server path /', () => { describe('GET', () => { it('makes a call to API', async () => {

当用户访问我的应用程序主页时,我的express后端向外部API发出RESTful http请求,该请求返回JSON

我想测试我的应用程序是否正在进行API调用(而不是实际进行调用)。我目前正在摩卡和Chai一起测试,并一直在使用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
    });
  });
});

我不关心服务器给出的响应,我只想检查我的应用程序是否使用正确的路径和标题(使用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('/')
      ...   
    });
  });
});

希望它能给你启发

先生,你是个传奇人物。非常感谢。