Jest beforeAll() share between multiple test files

You can move your beforeAll logic into one file and reference it in jest.config.js setupFilesAfterEnv section:

module.exports = {
...
setupFilesAfterEnv: ['<rootDir>/testHelper.ts'],
...
}

https://jestjs.io/docs/en/configuration#setupfilesafterenv-array


I am using a simple "test hooks" pattern for this:

// This function wraps beforeAll and afterAll into a single RAII-like call.
// That makes the describe code further down easier to read and makes
// sure you don't forget the afterAll part. Can easily be shared between tests.
function useFakeServer() {
  let server;

  beforeAll(() => server = sinon.fakeServer.create());
  afterAll(() => server.restore());
  
  return () => server;
}

describe('Some scenario', () => {
  const getServer = useFakeServer();
  
  it('accesses the server', () => {
    const server = getServer();
    // Test as you normally would..
    expect(server.requests[0]. /* ... */);
  });
});

If you're using Jest >=20, you might want to look into creating a custom jest-environment for the tests that require this common setup. This would be a module that extends either jest-environment-node or jest-environment-jsdom, and implements async setup(), async teardown(), and async runScript() to do this setup work.

You can then add a @jest-environment my-custom-env directive to those files that require this setup.

See the Jest config docs for testEnvironment for details on how to set this up; there's a simple example there.


If you need a script to run before all your test files, you can use globalSetup

This option allows the use of a custom global setup module which exports an async function that is triggered once before all test suites.

in your jest.config.js

//jest.config.js
module.exports = {
  ...
  testTimeout: 20000,
  globalSetup: "./setup.js"
};

then create a file named setup.js

// setup.js
module.exports = async () => {
    
    console.log("I'll be called first before any test cases run");
    //add in what you need to do here

};

Docs

Tags:

Jestjs