jest global variable example

Jestjs

Jestjs Problem Overview


Can someone give an example on how to use jest globals?

{
  ...
  "jest": {
    "globals": {
      "__DEV__": true,
    }
  }
  ...
}

Do I specify the globals in the package.json file or do I create a folder with a js file where the globals should be defined?

Thanks

Jestjs Solutions


Solution 1 - Jestjs

Yep. You put the globals in the package.json. For example, here's an excerpt from the default react-native jest configuration:

"jest": {
    "globals": {
       "__DEV__": true,
       "__RCTProfileIsProfiling": false
     },
     ...
},

This will make the variables available globally when the tests are run.

Solution 2 - Jestjs

A cleaner way to add globals would be to set "setupFiles": "<rootDir>/private/jest/setup.js" in package.json, and then create a setup.js file that sets global.__DEV__ = true.

This pattern is helpful for making 3rd party libraries available as globals to Jest tests as well (like Backbone, jQuery, lodash, etc.) - eg. global.Backbone = require('backbone'); and so on.

(Re-submitting this as an answer as it was previously just a comment under Michael Helvey's answer.)

Solution 3 - Jestjs

For me using the Jest config file worked much better because it is a Javascript file itself so it gives full freedom:

After running jest --init in your folder, in the jest.config.js file Jest makes, scroll down to find:

// A set of global variables that need to be available in all test environments
// globals: {},

Uncomment the second line and put all your globals in there.

Solution 4 - Jestjs

If you are using create-react-app, you must use the src/setupTests.js file instead of pointing to a file via setupFiles in the package.json file.

https://create-react-app.dev/docs/running-tests/#srcsetuptestsjs

In the src/setupTests.js file, you can define globals like so:

global.TIMEOUT = 3000;

Solution 5 - Jestjs

To share object variables (not only primitives as with configuration's globals property), you can use the testEnvironment property.

More explanations here in Jest's Git

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
QuestiontadalendasView Question on Stackoverflow
Solution 1 - JestjsMichael HelveyView Answer on Stackoverflow
Solution 2 - JestjsnickangView Answer on Stackoverflow
Solution 3 - JestjsArmanView Answer on Stackoverflow
Solution 4 - JestjsSteveView Answer on Stackoverflow
Solution 5 - JestjstaubhiView Answer on Stackoverflow