I would like some assistance in resolving this error.

Am using Jest V28.0.0.
Here's how my package.json's test script & devDependencies look like
    "scripts":{
       ...,
       "test": "jest --env=node --watchAll --coverage --verbose",
    },
   "devDependencies": {
        ...
        "@babel/preset-env": "^7.16.11",
        "@testing-library/jest-dom": "^4.2.4",
        "@testing-library/react": "^9.3.0",
        "@types/jest": "^27.4.1",
        "babel-jest": "^28.0.0",
        "jest": "^28.0.0",
        "jest-environment-jsdom": "^28.0.1",
        "jsdom": "^19.0.0",
    }
}
I also have a jest.config.js file that looks like so
module.exports = {
    roots: ['<rootDir>/tests/'],
    testEnvironment: 'jsdom',
    testMatch: ['**/?(*.)+(test).js'],
    transform: {
        '^.+\\.js?$': 'babel-jest',
    },
    moduleNameMapper: {
        ...
    },
}
My actual test file looks like so
import React from 'react'
import { render, cleanup, screen } from '@testing-library/react'
import renderer from 'react-test-renderer'
import '@testing-library/jest-dom'
/**
 * @jest-environment jsdom
 */
//components
import MyComponent from '../../../../src/website/Components/MyComponent'
test('should have the Add recipients text label', () => {
    const addRecipientsLabel = screen.getByTestId('label-element')
    expect(true).toBe(true)
    render(<MyComponent />)
    expect(addRecipientsLabel).toHaveTextContent('Add Recipients')
})
                You need to include @jest-environment at the top of the file. Above even the imports.
https://jestjs.io/docs/configuration#testenvironment-string
Eg.:
/**
 * @jest-environment jsdom
 */
import React from 'react'
      
//components
import MyComponent from '...'
test('should have the Add recipients text label', () => {
    // test
})
                        (OP already did this, but documenting for future visitors.)
As of Jest 28.x, if you are using JSDOM test environment, the jest-environment-jsdom package now must be installed separately:
npm install --save-dev jest-environment-jsdom
OR
yarn add --dev jest-environment-jsdom
Migration guide:
https://jest-archive-august-2023.netlify.app/docs/28.x/upgrading-to-jest28#jsdom
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With