When a user visits the homepage of my app, my express backend makes a RESTful http request to an external API, that returns a JSON.
I want to test that my app is making that API call (without actually making it). I'm currently testing in Mocha with Chai, and have been using Sinon and 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
});
});
});
I don't care about the response that the server gives, I just want to check that my app is making the call with the correct path and headers (with api keys etc..)
What I have done in the past for this scenario is I stubbed the server call using Sinon. Let's say you have a method for your server call
// server.js
export function getDataFromServer() {
// call server and return promise
}
in the test file
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('/')
...
});
});
});
Hope it can give you insights.