引用错误:窗口,请考虑使用“jsdom”测试环境(jest V28)

wljmcqd8  于 2022-12-08  发布在  Jest
关注(0)|答案(2)|浏览(173)

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

fykwrbwg1#

您需要显式安装JSDOM env。请参阅迁移指南https://jestjs.io/docs/28.x/upgrading-to-jest28#jsdom

gojuced7

gojuced72#

你需要在文件的顶部包含@jest-environment。甚至在导入的上面。
https://jestjs.io/docs/configuration#testenvironment-string
例如:

/**
 * @jest-environment jsdom
 */

import React from 'react'
      
//components
import MyComponent from '...'

test('should have the Add recipients text label', () => {
    // test
})

相关问题