vijayst
vijayst

Reputation: 21836

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.

Upvotes: 15

Views: 19667

Answers (4)

Moika Turns
Moika Turns

Reputation: 801

The jest dev server can stand up / down one or more local servers for each test run, exposing a cache on an endpoint would be one way to persist data across tests / suits. Albeit a hammer to crack a nut.

Upvotes: 0

Allen
Allen

Reputation: 4759

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

Upvotes: 7

andreialecu
andreialecu

Reputation: 3729

Setting an env variable like process.env.SESSION_KEY = sessionKey from globalSetup seems to work for me in subsequent tests.

I can access the value properly from any test. Not sure if this is a bug or a feature.

Upvotes: 6

Florian Richter
Florian Richter

Reputation: 141

I spend a lot of time figuring this out right. The only fully working solution was using testenvironments. This supports async functions as well as globals properly. Each test suite uses a separate instance of the testenvironment.

const NodeEnvironment = require('jest-environment-node');

class TestEnvironment extends NodeEnvironment {
  constructor(config) {
    super(config);
  }

  async setup() {
    await super.setup();
    this.global.db = await asyncCode();
  }

  async teardown() {
    this.global.db = null;
    await asyncCode2();
    await super.teardown();
  }

  runScript(script) {
    return super.runScript(script);
  }
}

module.exports = TestEnvironment;

I added a reference to this file in the Jest Config: "testEnvironment": "./testEnvironment" for the file testEnvironment.js

I'm not sure though why there are so many different config options like setupFiles, globals, testEnvironment, ...

Upvotes: 4

Related Questions