Search code examples
javascriptjestjsintegration-testing

How to use a Global Variable in Jest


I've got my Yarn package.json set up like this, where I create a global variable called localPath.

{
  "jest": {
    "globals": {
      "localPath": "Users/alex/Git/mytodolist"
    }
  }
}

Then, in one of my spec tests, I run

console.log(localPath)

but get this error.

ReferenceError: localPath is not defined

      5 | 
    > 6 |   console.log(localPath)

Does anyone know how to call the global variable you set up? I can only find articles on creating the variable, but not on how to call it.

Source: https://jestjs.io/docs/en/configuration#globals-object

Edit: Thanks to @slideshowp2 for the correct answer below. Turns out I didn't need to use a global variable in the end, as you can dynamically grab the execution path at run time. However, this will certainly be useful in the future.

beforeAll(async () => {
  await page.goto('file:///'+process.cwd()+'/index.html')
})

Solution

  • It should work. Here is a minimal working example:

    ./src/index.js:

    export function sum(a, b) {
      return a + b;
    }
    

    ./src/__tests__/index.spec.js:

    import { sum } from "../";
    
    it("should sum", () => {
      // eslint-disable-next-line
      console.log("localPath: ", localPath);
      const actualValue = sum(1, 2);
      expect(actualValue).toBe(3);
    });
    

    jest.config.js:

    module.exports = {
      preset: "ts-jest/presets/js-with-ts",
      testEnvironment: "node",
      coverageReporters: ["json", "text", "lcov", "clover"],
      testMatch: ["**/__tests__/**/*.[jt]s?(x)", "**/?(*.)+(spec|test).[jt]s?(x)"],
      globals: {
        localPath: "Users/alex/Git/mytodolist"
      }
    };
    

    Unit test result:

     PASS  src/__tests__/index.spec.js
      ✓ should sum (4ms)
    
      console.log src/__tests__/index.spec.js:5
        localPath:  Users/alex/Git/mytodolist
    
    Test Suites: 1 passed, 1 total
    Tests:       1 passed, 1 total
    Snapshots:   0 total
    Time:        2.233s
    Ran all test suites.
    

    As you can see, the value of global variable localPath has been set. Please print the global object and check in your tests.

    Codesandbox: https://codesandbox.io/s/unruffled-feistel-byfcc