Issue
I have this simple test:
import React from 'react'
import { render } from '@testing-library/react'
import Button from '.'
describe('Button', () => {
it('renders button without crashing', () => {
const label = 'test'
render(<Button label={label} />)
})
})
And I have a jest.config.json
with this content
{
"setupFilesAfterEnv": [
"<rootDir>/lib/settings/setupTests.ts"
]
}
And on my setupTests.ts
I have
import '@testing-library/jest-dom'
When I run npm run test
(which just run jest
), I got the following error:
The error below may be caused by using the wrong test environment, see https://jestjs.io/docs/configuration#testenvironment-string.
Consider using the "jsdom" test environment.
What I am doing wrong? This used to work before an upgrade.
Solution
In your package.json
, or jest.config.js
/jest.config.ts
file, change the value of the testEnvironment
property to jsdom
.
package.json
"jest":{
"testEnvironment": "jsdom"
}
jest.config.[js|ts]
module.exports = {
"testEnvironment": "jsdom"
}
Important note for jest >28
If you are using jest 28, you will need to install jest-environment-jsdom
separately by either:
npm: npm i jest-environment-jsdom --save-dev
yarn: yarn add -D jest-environment-jsdom
Why?
By default, jest uses the node
testEnvironment. This essentially makes any tests meant for a browser environment invalid.
jsdom
is an implementation of a browser environment, which supports these types of UI tests.
For Jest version 28 and greater, jest-environment-jsdom
was removed from the default jest
installation to reduce package size.
Additional reading
jest testEnvironment documentation
Answered By - Moistbobo
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.