Reputation: 28728
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: 52
Views: 52331
Reputation: 837
Update: As of Jest 26, the @jest/globals
package can be used to import
Jest functions:
import { describe, it, expect } from '@jest/globals'
Jest 26.5 further added the injectGlobals
config that you can set to false
to disable globals in your test files:
// jest.config.js
/** @type {import('jest').Config} */
const config = {
injectGlobals: false,
};
module.exports = config;
For versions of Jest older than 26, you can use the jest-without-globals
package as described below:
I similarly don't like using or relying on globals, 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 docs, 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: 9610
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: 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: 28728
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