Last updated: Mar 7, 2024
Reading timeยท2 min
The "Error: Test environment jest-environment-jsdom cannot be found" occurs
because starting with Jest version 28, the jest-environment-jsdom
package is
no longer shipped with jest.
Install the package separately to resolve the error.
Validation Error: Error: Test environment jest-environment-jsdom cannot be found. Make sure the testEnvironment configuration option points to an existing node module. As of Jest 28 "jest-environment-jsdom" is no longer shipped by default, make sure to install it separately.
Open your terminal in your project's root directory and run the following
command to install jest-environment-jsdom
.
# ๐๏ธ with NPM npm install jest-environment-jsdom --save-dev # ๐๏ธ with YARN yarn add jest-environment-jsdom --dev
Make sure that the testEnvironment
property is set to jsdom
in your
package.json
or jest.config.js
or jest.config.ts
file.
"jest": { "testEnvironment": "jsdom" }
And do the same if you use a jest.config.js
file.
module.exports = { "testEnvironment": "jsdom" }
Setting the
testEnvironment
property to jsdom
allows us to test in the browser. Note that jsdom
is the
default testEnvironment
in recent versions of jest.
If you are building a node service, set the testEnvironment
property to
node
.
You can also set the test environment on a per-file basis with a docstring.
/** * @jest-environment jsdom */ test('use jsdom in this test file', () => { const element = document.createElement('div'); expect(element).not.toBeNull(); });
If the error persists, install jest
and make sure that your jest
and
jest-environment-jsdom
versions match.
# ๐๏ธ with NPM npm install jest --save-dev npm install jest-environment-jsdom --save-dev # ๐๏ธ with YARN yarn add jest --dev yarn add jest-environment-jsdom --dev
jest
and jest-environment-jsdom
don't match, install a matching version of the packages.You can check your versions of jest
and jest-environment-jsdom
in the
devDependencies
section of your package.json
file.
Here is an example of installing version 29.3.1
of jest
and
jest-environment-jsdom
.
# ๐๏ธ with NPM npm install jest@29.3.1 --save-dev npm install jest-environment-jsdom@29.3.1 --save-dev # ๐๏ธ with YARN yarn add jest@29.3.1 --dev yarn add jest-environment-jsdom@29.3.1 --dev
If the error is not resolved, try to delete your node_modules
and
package-lock.json (not
package.json
) files, re-run npm install
and restart your test server.
# ๐๏ธ Windows - delete node_modules and package-lock.json rd /s /q "node_modules" del package-lock.json # ๐๏ธ macOS/Linux - delete node_modules and package-lock.json rm -rf node_modules rm -f package-lock.json # ๐๏ธ clean npm cache npm cache clean --force # ๐๏ธ install packages npm install
Make sure to restart your IDE and test server if the error persists. VSCode often glitches and needs a reboot.
You can learn more about the related topics by checking out the following tutorials: