Node.js 如何测试我的node/express应用程序正在进行API调用(通过axios)
当用户访问我的应用程序主页时,我的express后端向外部API发出RESTful http请求,该请求返回JSON 我想测试我的应用程序是否正在进行API调用(而不是实际进行调用)。我目前正在摩卡和Chai一起测试,并一直在使用Sinon和SupertestNode.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 () => {
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('/')
...
});
});
});
希望它能给你启发 先生,你是个传奇人物。非常感谢。