Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

168
Visualizações
Mocking req.user object for MochaJS tests

In one of my ExpressJS routes, I'm using PassportJS' HTTP Bearer Strategy and Local Strategy together. It means user must be logged in and must have a bearer token to reach that route.

function isLoggedIn(req, res, next) {

    // if user is authenticated in the session, carry on 
    if (req.isAuthenticated())
        return next();

    // if they aren't redirect them to the home page
    res.redirect('/login');
}
app.route('/api/someaction')
        .get(passport.authenticate('bearer', { session: false }), isLoggedIn, function(req, res, next) {
      console.log(req.user.userID);
});

When I browse to this route with my browser or with Postman (after setting cookies for local strategy) it's working as expected.

Now I need to write integration tests for this route with MochaJS/ChaiJS. This is my test file:

var server = require('../app.js');
var chai = require('chai');
var chaiHttp = require('chai-http');
var should = chai.should();
var expect = chai.expect;

chai.use(chaiHttp);

  describe('...', () => {
      it('...', (done) => {
        chai.request(server)
            .get('/api/someaction')
            .set('Authorization', 'Bearer 123')
            .end((err, res) => {
              // asserts here
              done();
            });
      });
});

While testing this file with MochaJS, req.user.userID in /api/someaction is always undefined.

How can I mock PassportJS strategies to get a req.user object inside route?

about 4 years ago · Santiago Trujillo
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda