简体   繁体   中英

ReferenceError: window is not defined, consider using the "jsdom" test environment (jest V28)

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
})

You need to install JSDOM env explicitly. See migration guide https://jestjs.io/docs/upgrading-to-jest28#jsdom

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM