Home > other >  Set an authentication token in a request header when using supertest with jest and express
Set an authentication token in a request header when using supertest with jest and express

Time:11-02

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?

CodePudding user response:

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);
  });
});

CodePudding user response:

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

  • Related