Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jest failing to run tests when importing globals

Tags:

jestjs

I'm trying to follow the advice in https://jestjs.io/docs/en/api about importing globals, namely this:

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

It doesn't work, though. I added the import at the top of my two test files and when I run jest, both test suites fail with the message "Do not import @jest/globals outside of the Jest test environment."

I also have jest configured in eslint env, in case it makes a difference.

Can someone point me in the right direction, please?

like image 553
borfast Avatar asked May 02 '20 11:05

borfast


People also ask

How is global in Jest defined?

This is often useful if you want to set up some global state that will be used by many tests. For instance: const globalDatabase = makeGlobalDatabase(); beforeAll(() => { // this clears the database and adds some testing data. // Jest waits for this promise to resolve before running tests. return globalDatabase.

What is Je beforeEach?

beforeEach(fn) #Runs a function before each of the tests in this file runs. If the function returns a promise, Jest waits for that promise to resolve before running the test. This is often useful if you want to reset some global state that will be used by many tests.

How do I import Jest?

The jest object is automatically in scope within every test file. The methods in the jest object help create mocks and let you control Jest's overall behavior. It can also be imported explicitly by via import {jest} from '@jest/globals' .

Do Jest tests run in parallel?

Each time a test run completes, the global environment is automatically reset for the next. Since tests are standalone and their execution order doesn't matter, Jest runs tests in parallel.


1 Answers

I just found out what the problem was: I was importing the @jest/globals package in a helper file which isn't a test file. Removing the import from there and leaving it only in the two test files allows Jest to run without a problem.

like image 141
borfast Avatar answered Sep 28 '22 00:09

borfast