'How can I import Jest?

I would like to get rid of global variables in my Jest test code. Specifically describe, it and expect:

describe('Welcome (Snapshot)', () => {
  it('Welcome renders hello world', () => {
     ...
  });
});

So I tried to add:

import {describe,it} from 'jest';

and

import jest from 'jest';

jest.describe( ...
  jest.it( ...

And other variations...

But no luck.

How should I get it working?



Solution 1:[1]

The simplest solution for this is adding jest: true to your env configuration in ESLint, like so:

"env": {
  "browser": true,
  "node": true,
  "jasmine": true,
  "jest": true,
  "es6": true
},

Solution 2:[2]

Try the code below:

import {describe, expect, it } from '@jest/globals'

if you prefer explicit imports, you can do import {describe, expect, test} from '@jest/globals'.

Source https://jestjs.io/docs/en/api

Solution 3:[3]

I similarly don't like using or relying on global variables, and after copy/pasting various workarounds in different projects, I decided to create jest-without-globals as a very tiny wrapper to support importing Jest's features.

Per the usage documentation, it's straightforward to use:

import { describe, it, expect } from 'jest-without-globals'

describe('describe should create a section', () => {
  it('it should checkmark', () => {
    expect('').toBe('')
   })
})

All of the functions available in Jest's API, as well as jest and expect, can be imported from jest-without-globals.

Using jest-without-globals, I don't need to copy/paste workarounds anymore and don't need to configure settings like ESLint's jest environment, it just works as a simple import.

It's also written in TypeScript, so you have typings out-of-the-box and it's fully tested to ensure it keeps working correctly.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Peter Mortensen
Solution 2
Solution 3 Peter Mortensen