为 SuperTest 中的测试全局获取和存储令牌

Get and store token globally for tests in SuperTest

我用Jest + SuperTest来测试API。我想获取令牌并将其全局存储(使用 agent() 方法。当我有硬编码令牌并使用 agent() 像这样全局设置它时它工作正常:

const supertest = require("supertest");
const baseUrl = "https://gorest.co.in/public/v1";

const request = supertest
  .agent(baseUrl)
  .set(
    "Authorization",
    ">>>here comes hardcoded token value<<<"
  );
describe("Posts endpoint", () => {
  it.only("should be able to create a post", async () => {
    const resp = await request.get("/users");
    const user_id = resp.body.data[0].id;

    const response = await request.post("/posts").send({
      title: "foo",
      body: "bar",
      user_id: user_id,
    });
    expect(response.statusCode).toBe(201);
  });
});

但我不知道如何从 auth 端点获取令牌并将其传递到那里而不是这个硬编码的。这里是beforeAll()中获取token的函数。

let token = "";

beforeAll(async () => {
  const response = await request(baseUrl).post("/auth").send({
      username: "test@example.com",
      password: "password",
    });
  token = response.body.access_token;
});

有人知道如何用 SuperTest 处理吗?

我认为你的代码顺序有点不对。虽然有些函数在测试时会被提升,但按照它应该执行的方式编写代码可能会更清楚。

你有写的想法,因为 beforeAll() 在 beforeEach 或其他测试之前执行。这个问题是您在 运行 beforeAll 并获取令牌之前在 Supertest 中创建请求。

const supertest = require("supertest");
const baseUrl = "https://gorest.co.in/public/v1";

describe("Posts endpoint", () => {

    let token = "";
    beforeAll(async () => {
        const response = await request(baseUrl).post("/auth").send({
            username: "test@example.com",
            password: "password",
        });
        token = response.body.access_token;
    });

    let request;
    beforeEach(async () => {
        request = supertest
            .agent(baseUrl)
            .set('Authorization', token)
        ;
    });

    it.only("should be able to create a post", async () => {
        const resp = await request.get("/users");
        const user_id = resp.body.data[0].id;

        const response = await request.post("/posts").send({
            title: "foo",
            body: "bar",
            user_id: user_id,
        });
        expect(response.statusCode).toBe(201);
    });
});