I am attempting to test middleware functions in my Express application using supertest and nock, but am having issues where the routes I have setup are checked by an earlier piece of middleware to ensure a session property exists on the incoming req
object.
I need to somehow mock out the session object prior to running the tests, but am unsure how to approach this. First let me share some code:
router.js
app.use('/api', helpers.hasAccessToken, require('./routes.js'));
routes.js
router.route('/*')
.get(routesController.fetch)
helpers.js
module.exports.hasAccessToken = function(req, res, next) {
if(req.session.accessToken){
next();
} else {
res.status(401).send('LOGIN_SESSION_ENDED');
}
};
routesController.js
module.exports.fetch = function(req, res) {
var options = helpers.buildAPIRequestOptions(req);
request(options, function(err, response, body){
res.status(response.statusCode).send(body);
});
};
routesController.spec.js
var app = require('./index.js'),
request = require('supertest')(app),
expect = require('chai').expect,
nock = require('nock');
describe('GET requests', function(){
beforeEach(function(){
nock('https://10.105.195.12:8243')
.get('/v1/schemes')
.reply(200, {foo:'bar'});
});
it('should return a 200 HTTP status code', function(done){
request
.get('/api/schemes')
.end(function(err, res){
expect(res.status).to.equal(200);
done();
});
});
});
My test fails as the value for res.status
is 401. I am using express-session, but I wondered if there was some way I could get at the req.session
object in my test suite and set the value of the accessToken property prior to running any of the tests.
Can anyone offer any advice\thoughts please?
Thanks