Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

297
Views
How can I pass my bearer token to next next tests

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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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: "test@example.com",
  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);
});

});
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!