Jest run code before and after all of the tests

Viewed 51

I would like to run code before and after all the tests, not file wide, test wide. For example;

Before starting the e2e tests, I would like to run the server in test mode with the database. After all, I would like to flush my db and close the processes.

I don't know if it is possible but I also would like to have a global db variable to do tests. What I am currently doing is like this:

describe("Posts Module", () => {
  let dbService: DatabaseService;

  beforeAll(async () => {
    dbService = new DatabaseService();
    await dbService.init();
  });

  it("should give the posts", () => {
    supertest(app)
      .get("/posts")
      .expect(200)
      .then(async (response) => {
        const dbPosts = await dbService.getPosts();
        expect(response.body).toBeDefined();
        expect(response.body.posts).toEqual(dbPosts);
      });
  });

  afterAll(async () => {
    await flushDb(dbService);
    await dbService.close();
  });
});

But what I actually want is initing this database service only once before all of the module tests (also starting the server, currently I start the server manually and run the tests afterwards).

0 Answers
Related