Reputation: 28598
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('Welcome (Snapshot)', () => {
jest.it('Welcome renders hello world', () => {
// ...
});
});
And other variation but it's not working.
How can I get my Jest test code working without globals?
Upvotes: 50
Views: 51658
Reputation: 9581
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
Upvotes: 35
Reputation: 740
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
andexpect
, can be imported fromjest-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.
Upvotes: 6
Reputation: 2403
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
},
Upvotes: 33
Reputation: 28598
After I realized Jest is running in Node.js, it realized I could do this:
let { describe, it } = global;
It is not perfect, but one step closer... now I don't need to configure my linter with global variables any more.
Upvotes: 25