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

370
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
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