我怎样才能将我的不记名令牌传递给下一个下一个测试

How can I pass my bearer token to next next tests

我想获取我的不记名令牌,将其保存并传递给下一个测试,但是当我尝试这样做时,令牌未通过,当我在测试中打印令牌时,我可以看到“未定义”

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

如何将此令牌传递给下一个测试?

尝试在之前使用'async':

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

我有类似的案例,效果很好:

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

});