如何测试我的节点/快速应用程序正在进行 API 调用(通过 axios)



当用户访问我的应用程序的主页时,我的快速后端会向外部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('/')
...   
});
});
});

希望它能给你一些见解。

最新更新