I'm trying to test a rest api which calls an external service.
server.js:
const express = require('express');
const app = express();
const router = express.Router();
const redirectUrl = require('../utils/redirection')
let baseUrl = 'myUrl';
let externalUrl = 'externalUrl';
router.get('/redirect', async (req, res) => {
const { productName } = req.query;
baseUrl = baseUrl + '/' + productName;
externalUrl = externalUrl + '/' + productName;
await redirectUrl(res)(timeOut, externalUrl, baseUrl)
})
app.use(router);
app.listen(3000);
utils/redirection.js:
redirectUrl = res => (timeOut, url, redirectUrl) => {
return new Promise((resolve, reject) => {
let cleared = false;
const timer = setTimeout(() => {
cleared = true;
return resolve(res.redirect(302, redirectUrl));
}, timeout);
return fetch(url)
.then(
response => {
if (!cleared) {
clearTimeout(timer);
const {location} = response.headers;
return resolve(res.redirect(302, location));
}
return null;
})
.catch(err => {
if (!cleared) {
clearTimeout(timer);
return reject(err);
}
});
});
}
test.js:
const requrest = require('request');
const chai = require('chai');
const server = require('../server/server');
const { expect } = chai;
describe('My test', () => {
it('should redirects to the suitable page', () => {
const { status, headers } = request(app).get('/redirect')
expect(status).to.equal(302);
expect(headers.location).to.not.equal(0);
})
})
So, the test executes the api by providing the provided baseUrl
and externalUrl
which are set in the environment configuration. However, I wan to mock the call of redirectUrl
when the route would be tested. I tried to use nock
:
const request = require('request');
const chai = require('chai');
const server = require('../server/server');
const { expect } = chai;
const nock = require('nock');
describe('My test', () => {
it('should redirects to the suitable page', () => {
nock('fake url')
.get(`/${productName}`)
.reply(302, {
headers: { location: 'url/to/redirect/page'}
})
const { status, headers } = request(app).get('/redirect')
expect(status).to.equal(302);
expect(headers.location).to.not.equal(0);
})
})
When executing the test, the nock mock has never been called. Any suggestion to mock the function call of redirectUrl
inside a rest api?
Aucun commentaire:
Enregistrer un commentaire