Jest run async function ONCE before all tests

JavascriptJestjs

Javascript Problem Overview


I want to use jest for my server unit testing (instead of mocha+chai). Is there a way I can run async function before all tests start (init purposes) only once and not for every test file? And also if there's a way of running something after all tests are done?

Javascript Solutions


Solution 1 - Javascript

This feature was added in Jest's 22 version, with globalSetup and globalTeardown configurations. Look at this for examples.

package.json (or in jest.config.js)

{
  ...
  "jest": {
    "globalSetup": "./scripts/jestGlobalSetup.js"
  }
}

/scripts/jestGlobalSetup.js

module.exports = async () => {
  console.log('\nhello, this is just before tests start running');
};

OR

export default async () => {
  console.log('\nhello, this is just before tests start running');
};

Solution 2 - Javascript

Jest provides beforeAll and afterAll. As with test/it it will wait for a promise to resolve, if the function returns a promise.

beforeAll(() => {
  return new Promise(resolve => {
    // Asynchronous task
    // ...
    resolve();
  });
});

It also supports callback style, if you have some existing test code that uses callbacks, although it's recommended to use promises.

beforeAll(done => {
  // Asynchronous task
  // ...
  done();
});

Solution 3 - Javascript

jest provides options for both global setup and teardown in new versions. You can create files for both setup and teardown exporting an async function and provide that path in jest configurarion like this.

"globalSetup": "setup-file-path",
"globalTeardown": "tear-down-file-path"

You can read about it further here

Solution 4 - Javascript

If you execute jest tests with npm you can run any node command or any executable before executing other command

"scripts": {
    "test": "node setup.js && jest"
  }

so now you can run this with command

$ npm t

Solution 5 - Javascript

It's become very easy when you use beforeAll function outside the describe block and then assign async keyword to it.

Note: I am using jest @27.4.3 version here

> code sample

import { getValuesFromAWSSecretManager } from '../../src/libs/secret_manager';
import quickbooksConfigFrom from '../../src/config/quickbooks';

const quickbooksConfig = quickbooksConfigFrom;

// calling the async beforeALL function to get values from AWS Secret Manager
beforeAll(async () => {
  const secretData = await getValuesFromAWSSecretManager();
  quickbooksConfig.clientId = secretData.QUICKBOOKS_CLIENT_ID;
  quickbooksConfig.clientSecret = secretData.QUICKBOOKS_CLIENT_SECRET;
});

describe('Quickbooks config file should be defined', () => {
  test('Quickbooks File should be exist', () => {
    expect(quickbooksConfig).toBeDefined();
  });

  test('Quickbooks File should be exist and having values', () => {
    expect(quickbooksConfig).toBeTruthy();
  });
});

hope it helps and solves your doubts,

and you might need to do it in each file to apply.

you can check jest beforeAll documentation from here

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRoyView Question on Stackoverflow
Solution 1 - JavascriptAmaury LietView Answer on Stackoverflow
Solution 2 - JavascriptMichael JungoView Answer on Stackoverflow
Solution 3 - JavascriptRaheel RiazView Answer on Stackoverflow
Solution 4 - JavascriptLauri LüüsView Answer on Stackoverflow
Solution 5 - JavascriptRaj GohilView Answer on Stackoverflow