我正在next-js上编写一个web应用程序(带有typescript和styleed组件(。我开始写测试,当使用装载时,一个错误导致崩溃
TypeError: Cannot read property 'child' of undefined
但如果我使用浅层,一切都有效。我需要使用mount来渲染组件中的所有元素,因为如果我使用浅层、样式化的组件,它的组件就不会渲染,我也无法模拟它上的事件。我不明白有什么问题
SmartText.test.tsx:
import React from 'react'
import { mount, ReactWrapper } from 'enzyme'
import {SmartText} from '../components/UI/SmartText'
describe('Render UI', () => {
let component: ReactWrapper
beforeEach(() => {
component = mount(<SmartText/>)
})
describe('SmartText', () => {
test('Snapshot', () => {
expect(component).toMatchSnapshot()
})
test('Input text', () => {
component.find('input').simulate('change', {
target:{
value: 'some'
}
})
expect(component.find('input').prop('value')).toEqual('some')
})
})
})
包.json
{
"name": "task-manager",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next b
uild",
"start": "next start",
"storybook": "start-storybook -p 6006",
"build-storybook": "build-storybook",
"test": "jest ",
"test:watch": "jest --watch",
"test:coverage": "jest --coverage",
"prettier": "prettier --check ./"
},
"dependencies": {
"enzyme-adapter-react-16.3": "^1.7.3",
"next": "9.5.5",
"react": "17.0.1",
"react-dom": "17.0.1"
},
"devDependencies": {
"@babel/core": "^7.12.3",
"@babel/plugin-transform-runtime": "^7.12.1",
"@babel/preset-env": "^7.12.1",
"@babel/preset-flow": "^7.12.1",
"@babel/preset-react": "^7.12.1",
"@storybook/addon-actions": "^6.0.27",
"@storybook/addon-essentials": "^6.0.27",
"@storybook/addon-links": "^6.0.27",
"@storybook/react": "^6.0.27",
"@types/enzyme": "^3.10.7",
"@types/enzyme-adapter-react-16": "^1.0.6",
"@types/jest": "^26.0.15",
"@types/node": "^14.14.2",
"@types/react": "^16.9.53",
"@types/styled-components": "^5.1.4",
"babel-jest": "^26.6.1",
"babel-loader": "^8.1.0",
"babel-plugin-transform-es2015-modules-commonjs": "^6.26.2",
"enzyme": "^3.11.0",
"enzyme-adapter-react-16": "^1.15.5",
"enzyme-to-json": "^3.6.1",
"jest": "^26.6.1",
"jest-styled-components": "^7.0.3",
"prettier": "^2.1.2",
"react-is": "^17.0.1",
"react-test-renderer": "^17.0.1",
"sb": "^6.0.27",
"styled-components": "^5.2.0",
"ts-jest": "^26.4.1",
"typescript": "^4.0.3"
},
"resolutions": {
"styled-components": "^5"
}
}
出现此问题的原因是enzyme-adapter-react-16
版本与17时的react
版本不兼容。
您可以降级到react 16,也可以回退到此处描述的临时解决方案来升级enyzme适配器:https://github.com/wojtekmaj/enzyme-adapter-react-17
安装此包并导入
步骤1:npm安装@wojtekmaj/酶适配器-反应-17
步骤2:用从'@wojtekmaj/酶-Adapter-rect-17'导入适配器替换来自'zyme-Adapter-Rect-16'的导入适配器
你可以走了。