I am currently working on testing the routes within my express
application that are secured by a jwt middleware. To attempt to retrieve the jwt token in a test setup, I have utilized a simulated request within a beforeAll
function:
let token = "";
beforeAll((done) => {
supertest(app)
.get("/authentication/test")
.end((err, response) => {
console.log(response.body); // "fewiu3438y..." (token successfully retrieved)
token = response.body.token; // Attempted to update the token variable with jwt token
done();
});
});
console.log(token); // "" (Token variable not updated)
As a result, when trying to execute subsequent tests, authentication fails due to the absence of a valid token for headers:
describe("Simple post test using auth", () => {
test.only("should respond with a 200 status code", async () => {
console.log({ POSTTest:token }); // "" still not set, causing test to fail.
const response = await supertest(app).post("/tests/simple").send();
expect(response.statusCode).toBe(200);
});
});
Is there an effective way to update a variable or set all headers using a beforeAll
? Alternatively, is there a more efficient method that I may be unaware of?