Uncaught TypeError: Cannot read properties of undefined (reading 'isBatchingLegacy')

Uncaught TypeError: Cannot read properties of undefined (reading 'isBatchingLegacy')

我正在尝试使用 jest 测试一个 React TypeScript 项目,但它给出了一个令人困惑的错误:

Error image

这是我的 package.json:

"dependencies": {
    "@testing-library/jest-dom": "^5.16.4",
    "@testing-library/react": "^12.1.5",
    "@testing-library/user-event": "^13.5.0",
    "@types/jest": "^27.4.1",
    "@types/node": "^16.11.26",
    "@types/react": "^17.0.43",
    "@types/react-dom": "^17.0.14",
    "jest": "^27.5.1",
    "react": "^17.0.2",
    "react-dom": "^17.0.2",
    "react-router-dom": "^6.2.2",
    "react-scripts": "5.0.0",
    "ts-jest": "^27.1.4",
    "typescript": "^4.6.3",
    "web-vitals": "^2.1.4",
},

"devDependencies": {
    "@types/react-test-renderer": "^18.0.0",
    "react-test-renderer": "^18.1.0"
}

我写了这个给出错误的基本测试:

import renderer from 'react-test-renderer'
import AddShipmentButton from './AddShipmentButton'

it('works', () => {
    const tree = renderer.create(<AddShipmentButton />).toJSON()
    expect(tree).toMatchSnapshot()
})

我必须使用 --legacy-peer-deps 安装依赖项。可能是什么问题?提前致谢。

像这样升级您的应用依赖项

"react": "~18.0.0",
 "react-dom": "^18.0.0", 
 "react-test-renderer": "^18.0.0"

React 文档中定义的导入错误,尝试这种方式

import TestRenderer from 'react-test-renderer';

import AddShipmentButton from './AddShipmentButton'

it('works', () => {
  const tree = TestRenderer.create(<AddShipmentButton />).toJSON()
  expect(tree).toMatchSnapshot()
})

阅读 TestRenderer 的用法here

问题是我安装了最新版本的react-test-rendererv18.0.1,而React版本是v17.0.2。安装 react-test-renderer 版本 17.0.2 解决了这个问题。