Using Mocha/Chai for REST API unit testing, I need to be able to mock req.session.someKey
for a few of the end points. How can I go about mocking req.session
?
I'm working on writing REST API unit tests for a NodeJS Express app that utilizes express-session. Some of these endpoints require the use of data stored in req.session.someKey
, the endpoint is setup to return a 400 if req.session.someKey
is undefined so I need to be able to mock it in order for the test to complete successfully.
Example code:
router.get('/api/fileSystems', utilities.apiAuth, (req, res) => {
let customer = req.session.customer;
let route = (customer === 'NONE') ? undefined : customer;
if(route == undefined){
res.status(400).send('Can't have customer of undefined');
} else {
let requestOptions = setRequestOptions(route);
queryFileSystemInfo(requestOptions, (info) => {
res.status(200).send(info);
});
}
});
What I've tried:
describe('/GET /api/fileSystems', () => {
it('It should return information about the filesystem for a customer'), (done) => {
chai.request(server)
.get('api/fileSystems')
.set('customer', '146')
.end((err, res) => {
res.should.have.status(200);
done();
});
});
});
I attempted to use the .set()
in order to set req.session but I believe that .set just sets the headers so I don't believe that I can update it that way unless I'm missing something.
For this project, I ended up having to set req.session.customer
in our server.js file that has an app.use()
call that uses a middleware function to set the current session. I was unable to actually find a package that directly mutates the req.session object at test time.