Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

371
Vistas
Set an authentication token in a request header when using supertest with jest and express

I'm trying to test the routes in my express app that are protected by a jwt middleware. I've tried simulating a request to get the jwt token in a beforeAll call:

let token = "";
beforeAll((done) => {
    supertest(app)
        .get("/authentication/test")
        .end((err, response) => {
            console.log(response.body); // "fewiu3438y..." (successfully got token) 
            token = response.body.token; // Tried to update token variable with jwt token
            done();
        });
});
console.log(token); // "" (I haven't updated the token variable) 

So when I try to run subsequent tests, I don't have a valid authentication token to use in the headers:

    describe("Simple post test using auth", () => {
        test.only("should respond with a 200 status code", async () => {
            console.log({ POSTTest:token }); // "" still not set, so test will fail.
            const response = await supertest(app).post("/tests/simple").send();
            expect(response.statusCode).toBe(200);
        });
    });

Is there a way to update a variable, or else set all headers using a beforeAll? Or is there a better method I'm not aware of?

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

Try to use an async function as a beforeAll callback:

let token = '';

beforeAll(async () => {
  const response = await supertest(app).get('/authentication/test');
  token = response.body.token;
});

Then, use the set method to pass the token in the test:

describe('Simple post test using auth', () => {
  test.only('should respond with a 200 status code', async () => {
    const response = await supertest(app)
      .post('/tests/simple')
      .set('Authorization', `Bearer ${token}`);

    expect(response.statusCode).toBe(200);
  });
});
about 4 years ago · Juan Pablo Isaza Denunciar

0

I am doing like this

    import * as request from 'supertest';

    describe('Simple post test using auth', () => {
    test.only('should respond with a 200 status code', async () => {
     const res = await request(app.getHttpServer())
      .post('/tests/simple')
      .send(payload)
      .set('Authorization', `Bearer ${token}`);

    expect(res.statusCode).toBe(200);
  });
});

Also I have a suggestion that you mock your authentication request. Here is similar question for that if you are using jest Mock Authentication Request -Jest

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda