Trey Granderson
Trey Granderson

Reputation: 710

Jest beforeAll() and afterAll() from different test are running one after the other

I am trying to use beforeAll and afterAll methods to setup and teardown database after every test suite. However all the beforeAll functions run one after the other. The expected behavior according to (the docs)[https://jestjs.io/docs/api#beforeallfn-timeout] is that beforeAll and afterAll inside a describe should only run at the beginning of the describe block.

Here is an example of my code.

test-file-1.ts

describe("POST endpoint", () => {
  beforeAll(async () => {
    console.log("✨ Seeding DB for createBooking tests...");

    const createProperty = await prisma.property.create({});

    console.log("✨ DB seeded for createBooking test!");
  });

  afterAll(async () => {
    await clearDB();

    await prisma.$disconnect();

    console.log("✨ DB successfully cleared!");
  });
});

test-file-2.ts

describe("PUT endpoint", () => {
  beforeAll(async () => {
    console.log("✨ Seeding DB for updateBooking tests...");

    const createProperty = await prisma.property.create({});

    console.log("✨ DB seeded for updateBooking test!");
  });

  afterAll(async () => {
    await clearDB();

    await prisma.$disconnect();

    console.log("✨ DB successfully cleared!");
  });
});

When I run these tests, the following is logged to the console, which conveys that the beforeAll functions from each test file are running synchronously with one another.

    ✨ Seeding DB for createBooking tests...

    ✨ Seeding DB for updateBooking tests...

    ✨ DB seeded for createBooking test!

    ✨ DB seeded for updateBooking test!

And then the test suites run. Why are the beforeAll and afterAll functions not scoped to their respective contexts within the describe block? Am I doing something wrong?

Upvotes: 2

Views: 2333

Answers (1)

Ace
Ace

Reputation: 1146

Jest tests are run in parallel, not sequentially. So both test are started without waiting for the other to end. I could only find an off hand mention of it on their docs here

Note: the --runInBand cli option makes sure Jest runs the test in the same process rather than spawning processes for individual tests. Normally Jest parallelizes test runs across processes but it is hard to debug many processes at the same time.

Upvotes: 1

Related Questions