Reputation: 31
I want to test my routes with jest but I don't know how to mock or simulate a session in my test to pass the first if line 2
app.get('/getMailSuiviList', (req, res) => {
if (req.session.infoUser != undefined) {
let mail = require('../models/M_Email')
mail.indexSuiviByDept(req.session.infoUser.deptID)
.then(dataMails => {
res.json(dataMails)
})
.catch(e => {
res.json('Erreur: ' + e)
})
} else {
req.session.error = 'Vous devez vous connecter'
res.redirect('/')
}
})
Can someone help me?
Upvotes: 1
Views: 1519
Reputation: 114004
Could not find any way to do this with jest
or supertest
so I did it directly in Express
:
First, my routes/controllers are in their own files and I app.use()
them in my server.js
file. So instead of importing my server and test it I import my routes individually and test them separately. This allows me to inject a fake session middleware just for testing.
Say for example you have your route above in its own file:
// mail.js
const express = require('express');
const router = express.Router();
router.get('/getMailSuiviList', (req, res) => {
if (req.session.infoUser != undefined) {
let mail = require('../models/M_Email')
mail.indexSuiviByDept(req.session.infoUser.deptID)
.then(dataMails => {
res.json(dataMails)
})
.catch(e => {
res.json('Erreur: ' + e)
})
} else {
req.session.error = 'Vous devez vous connecter'
res.redirect('/')
}
})
module.exports = router;
Now in my test I do this:
const mailRouter = require('../mail.js');
const express = require('express');
const supertest = require('supertest');
const app = express();
const fakeSessionMiddleware = (req, res, next) => {
req.session = {
infoUser: {
deptID: 1
}
}
next();
}
app.use(fakeSessionMiddleware);
app.use(mailRouter);
describe('mail',() => {
it('should get mail', async () => {
// write your test here...
});
});
Upvotes: 0
Reputation: 1
Just in case you haven't, check supertest-session package, it's a wrapper around supertest and provides session auth in requests:
Upvotes: 0