Get and Store Token Globally for Tests in Supertest

I use Jest + SuperTest to test API. I would like to get the token and store it globally (using agent() method. It works fine when I have hardcoded token and use agent() to set it globally like this:

const supertest = require("supertest");
const baseUrl = "";

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

but I don't know how to get the token from auth endpoint and pass it there instead of this hardcoded one. Here is the function of getting token in beforeAll().

let token = "";

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

Does anyone have any idea how to handle that with SuperTest?

1 Answer

I think the order of your code is just slightly wrong. Although some functions get hoisted when testing, it might be clearer to write the code the way it should execute.

You have the write idea, as the beforeAll() is executed before a beforeEach or other test. This problem is that you are creating your request in Supertest before you run the beforeAll and get the token.

const supertest = require("supertest");
const baseUrl = "";

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

    let token = "";
    beforeAll(async () => {
        const response = await request(baseUrl).post("/auth").send({
            username: "",
            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);
    });
});
1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Robert Thorne

Robert Thorne

Automotive & Future Transportation Editor

Robert Thorne covers electric vehicle innovations, autonomous driving systems, global mobility trends, and automotive engineering developments.

Share this article
Twitter Facebook Pinterest