考虑使用 "jsdom" 测试环境

Consider using the "jsdom" test environment

我有这个简单的测试:

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

我有一个 jest.config.json 内容

{
  "setupFilesAfterEnv": [
    "<rootDir>/lib/settings/setupTests.ts"
  ]
}

在我的 setupTests.ts 上有

import '@testing-library/jest-dom'

当我运行npm run test(就是运行jest)时,我得到了以下错误:

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.

我做错了什么?这曾经在升级前工作。

在您的 package.jsonjest.config.js/jest.config.ts 文件中,将 testEnvironment 属性 的值更改为 jsdom

Package.json

"jest":{
    "testEnvironment": "jsdom"
}

jest.config.[js|ts]

{
    "testEnvironment": "jsdom"
}

关于笑话的重要提示 >28

如果您使用的是 jest 28,则需要通过以下任一方式单独安装 jest-environment-jsdom

npm: npm i jest-environment-jsdom --save-dev

纱线:yarn add -D jest-environment-jsdom

为什么?

默认情况下,jest 使用 node 测试环境。这实质上使任何针对浏览器环境的测试都无效。

jsdom是一个浏览器环境的实现,它支持这些类型的UI测试。

对于 Jest 版本 28 及更高版本,jest-environment-jsdom 已从默认 jest 安装中删除以减小包大小。

补充阅读

jest testEnvironment documentation

Jest 28 breaking changes

这可以在 per-test-file 的基础上通过在文件开头添加 @jest-environment 文档块来解决。例如:

/** @jest-environment jsdom */
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} />)
  })
})

如果您的项目混合了 UI 和 non-UI 文件,这通常优于 by setting "testEnvironment": "jsdom" within your package.json or Jest config. By skipping initializing the JSDom environment for non-UI tests, Jest can run your tests faster. In fact, that's why Jest changed the default test environment in Jest 27

默认情况下,testEnvironment 的值为 node,它在 node.js 环境中运行所有测试用例,但 js-dom 提供类似浏览器的环境。除了添加 jsdom 值,您甚至可以添加文件特定的值,如下所示。

/**
 * @jest-environment jsdom
 */
// the above comment helps
test('use jsdom in this test file', () => {
  const element = document.createElement('div');
  expect(element).not.toBeNull();
});

我们甚至可以添加测试文件特定环境,请参考此link。

https://jestjs.io/docs/configuration#testenvironment-string