jestjs

How do I save a value in global in Jest during test setup?


I have a global setup in Jest.

"jest": {
    "globalSetup": "./setup.js"
  }

Within the setup, I have an async function which writes a session key to global

const axios = require('axios');

async function getSessionKey() {
    const response = await axios.post("http://apiUrl", {
        username: "K",
        password: "passw0rd"
    });
    sessionKey = response.data.sessionKey;
    global.sessionKey = sessionKey;
}

module.exports = getSessionKey;

Whatever session key I am saving in global is not available in the test file. global.sessionKey is undefined in the below test.

test("create session", () => {
    expect(global.sessionKey).toBeTruthy();
});

I want some way to set the sessionKey in a global object from setup file. The session key should be available before I run any of my tests.


Solution

  • globalSetup/globalTeardown can't be used to inject context/global variables to sandboxed test suites/files. Use setupFiles/setupFilesAfterEnv instead.

    Other way you can customize the test runtime through testEnvironment, more details see here: Async setup of environment with Jest