Search code examples
typescriptpuppeteerts-jest

How use global variable in Jest and pass it through cmd


I'm trying to create some e2e tests via puppeteer and jest, and now I'm stuck with a problems regarding global variables. So I have 2 issues:

  1. How can I use globals in jest with puppeteer? Now I have the following in my jest.config.js
module.exports = {
    globals: {
        URL: "https://demoqa.com/",
        value: "myvalue"
      },
    preset: 'jest-puppeteer',
    testMatch: ["**/?(*.)+(spec|test).[t]s"],
    testPathIgnorePatterns: ['/node_modules/', 'dist'],
    setupFilesAfterEnv: ['<rootDir>/jest.setup.ts'],
    transform: {
        "^.+\\.ts?$": "ts-jest"
    },
    globalSetup: './jest.global-setup.ts',
    globalTeardown: './jest.global-teardown.ts',
    verbose: true
};

and then I'm trying to use globals in my src/tests/test.spec.ts like this:

console.log(URL.toString());
console.log(value.toString());

But this gives error that value is not defined, but URL has the right value as in the jest.config.js

What am I doing wrong?

  1. How can I pass this globals via command line? I found in jest docs the --globals flag, and tried to use it like this:

npm run jest -- --globals URL='someUrl', value='someValue'

but it doesn't work too.


Solution

    1. Use the global object (e.g global.value) to access globals in the tests

      console.log(global.value);
      
    2. Use the --globals parameter to override globals in the valid JSON format

      npm run jest -- --globals='{"URL": "someUrl", "value": "someValue"}'