Set an authentication token in a request header when using supertest with jest and express
Asked Answered
J

2

5

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?

Jazzman answered 1/11, 2021 at 9:25 Comment(0)
R
16

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);
  });
});
Rent answered 1/11, 2021 at 9:31 Comment(0)
A
1

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

Achromat answered 1/11, 2021 at 9:35 Comment(2)
Are you suggesting to turn off the security check for the token? What if I forget to protect the endpoint? When someone is writing a test like this (from outside), I assume they want to test everything.Maritzamariupol
I am suggesting to mock the request / response and not the actual endpoint this is only for testAchromat

© 2022 - 2024 — McMap. All rights reserved.