Reputation: 411
I want to get my bearer token, save it and pass it to the next tests, but when I try to do this, the token is not passed and when I print token in the test I can see "undefined"
import supertest from "supertest";
const baseUrl = "https://api.staging.myapi";
let token;
before(() => {
supertest("https://identitytoolkit.googleapis.com")
.post(
"/mykeyUrl"
)
.send({
email: "user",
password: "password",
returnSecureToken: true,
})
.set("Authorization", "bearer " + token)
.end((err, response) => {
token = response.body.idToken;
});
});
describe("Create an unit", () => {
console.log(token)
it("should create an unit", async () => {
console.log(token)
const res = await supertest(baseUrl)
.post("myUrl")
.send({
name: "SuperTestUni",
location: "Warsaw",
})
.set("Authorization", "bearer " + token)
.expect(201)
});
});
How can I pass this token to the next test?
Upvotes: 0
Views: 1292
Reputation: 50
Try to use 'async' in before:
before(async () => {
const response= await supertest("https://identitytoolkit.googleapis.com")
.post(
"/mykeyUrl"
)
.send({
email: "user",
password: "password",
returnSecureToken: true,
})
.set("Authorization", "bearer " + token)
.end((err, response);
token = response.body.idToken;
});
I have similar case which works fine:
let token = "";
beforeAll(async () => {
const response = await request(baseUrl).get("/auth").send({
username: "[email protected]",
password: "password",
});
token = response.body.access_token;
});
describe("Posts endpoint", () => {
it("should be able to create a post", async () => {
const response = await request(baseUrl)
.post("/posts")
.send({
title: "foo",
body: "bar",
user_id: 2139,
})
.set("Authorization",`Bearer ${token}`);
expect(response.statusCode).toBe(201);
});
});
Upvotes: 2