What is Jest's equivalent of Mocha's root-level hooks?

Viewed 905

I'm trying to write tests for my Node.js backend application with Jest. The backend has mongodb implementations via mongoose.

I need to have a global hook, in which I can connect to the database before running all tests in all test files.

In Mocha, I can do it easily as documented here:

You may also pick any file and add “root”-level hooks. For example, add beforeEach() outside of all describe() blocks. This will cause the callback to beforeEach() to run before any test case, regardless of the file it lives in (this is because Mocha has an implied describe() block, called the “root suite”).

So I could, for example, create a testHelper.js file and write:

const mongoose = require('mongoose');

// ./test/testHelper.js
before((done) => {
  const mongoURI = `${process.env.DB_MONGO_URI}/testdb`;
  mongoose.connect(mongoURI, { useNewUrlParser: true});
  mongoose.connection
    .once('open', done)
    .on('error', (error) => {
      console.warn(error);
      done();
    });
});

after(() => {
  mongoose.disconnect();
});

The above will run before and after all tests in all test files.

How can I do the same above with jest?

1 Answers

Jest API has beforeAll and afterAll for this purpose.

It shares the concept of top-level implied describe() block with Mocha, other blocks don't necessarily have to be placed inside describe, including beforeAll and afterAll.

Notice that due to that Jest tests run concurrently, beforeAll and afterAll will affect only current test environment, i.e. tests defined in the same file.

Related