Environment key “jest/globals” is unknown

The “jest/globals” environment key is used in the Jest testing framework. It specifies the global variables available during test execution. This key is used in the Jest configuration file (usually named “jest.config.js”) to set up the testing environment.

By default, Jest provides several built-in global variables such as “test”, “expect”, and “describe”. These globals allow you to write assertions and define test suites without explicitly importing them in every test file.

However, in some cases, you may have custom global variables or modules that you want to use in your tests. This is where the “jest/globals” environment key comes in.

To make Jest aware of custom global variables, you can define them in the “globals” object of your Jest configuration file. Here’s an example:

module.exports = {
  globals: {
    MY_GLOBAL_VARIABLE: true,
    ANOTHER_GLOBAL: 'hello'
  }
};

In this example, we define two global variables: “MY_GLOBAL_VARIABLE” and “ANOTHER_GLOBAL”. The values can be of any type, including numbers, strings, booleans, objects, or functions.

Once you’ve defined custom globals, you can directly use them in your test files without importing or declaring them. For example:

test('example test', () => {
  expect(MY_GLOBAL_VARIABLE).toBe(true);
  console.log(ANOTHER_GLOBAL); // outputs 'hello'
});

Here, we directly accessed the values of the custom global variables “MY_GLOBAL_VARIABLE” and “ANOTHER_GLOBAL” within a test case.

If you try to access a global variable that is not defined in the “jest/globals” configuration, Jest will throw an error, indicating that the environment key is unknown. Therefore, make sure to define all necessary globals within the configuration file to avoid such errors.

Related Post

Leave a comment