I want to write a test for my passport local auth. If auth is a success or failure in both scenarios the user gets redirected which sends a status 302. Since I can't distinguish between success or failed auth since the status codes are the same, so I decided to write custom methods (which is the not commented section) but when I send the 401 unauthorized status code it doesn't redirect the user it shows a page with a link to the redirect route.
How could you test passport auth using Jest and Supertest?
/*
app.post('/users/login', passport.authenticate('local', {
successRedirect: '/users/dashboard',
failureRedirect: '/users/login',
failureFlash: true,
}));*/
app.post('/users/login', (req, res, next) => {
passport.authenticate('local', (err, user, info) => {
if (err) return next(err);
if (!user) res.redirect(401, '/users/login'); // failure
req.logIn(user, (err) => {
if (err) return next(err);
return res.redirect('/users/dashboard'); //success
});
})(req, res, next);
});
Here is my Jest/Supertest test: In this case, the test will pass but on the front-end, the user wouldn't get redirected directly to the URL: '/users/dashboard'
test('should return a status code: 401', async () => {
const response = await request(app).post('/users/login').send({
// incorrect login
email: 'jane@gmail.com',
password: 'asdfa'
})
expect(response.statusCode).toBe(401)
})
})
Thank you
Edit: expect(response.headers['Location']).toEqual('/users/login'); seems to be what I need but response.headers['Location'] gives me undefined.
Test:
test('should redirect to /users/login', async () => {
const response = await request(app).post('/users/login').send({
email: 'jane@gmail.com',
password: 'incorrectPassword'
})
expect(response.headers['Location']).toEqual('/users/login');
})
new post route:
app.post('/users/login', passport.authenticate('local', {
successRedirect: '/users/dashboard',
failureRedirect: '/users/login',
failureFlash: true
}));