【发布时间】:2020-12-17 03:59:46
【问题描述】:
运行时出现以下错误
npm run test
src/components/documentEditor/levels/2_page/page.test.js
● Test suite failed to run
Cannot find module 'react' from 'styled-components.cjs.js'
However, Jest was able to find:
'./page.js'
'./page.test.js'
You might want to include a file extension in your import, or update your 'moduleFileExtensions', which is currently ['web.js', 'js', 'web.ts', 'ts', 'web.tsx', 'tsx', 'json', 'web.jsx', 'jsx', 'node'].
See https://jestjs.io/docs/en/configuration#modulefileextensions-array-string
我认为 {Cannot find module 'react' from 'styled-components.cjs.js'} 错误是指正在测试的“Page”组件中的导入
如果我不运行任何测试并且使用了 styledComponents 并且可以正常工作,那么“页面”组件会完美运行。
“页面”组件的标题看起来像这样(不是完整的组件,只是前几行)
import React from 'react';
import styled from 'styled-components';
import { Droppable, Draggable } from 'react-beautiful-dnd';
import { filterArrayByChildrenIds } from '../../functions/supportingFunctions/generic';
import ModifyPage from './modifyPage';
import Paragraph from '../3_paragraph/paragraph';
const Container = styled.div``;
const Title = styled.div``;
const VerticalList = styled.div`
package.JSON 中的 Jest 设置是这样的
{
"name": "client",
"version": "0.1.0",
"private": true,
"dependencies": {
"axios": "^0.19.0",
"enzyme-adapter-react-16": "^1.15.3",
"react": "^16.9.0",
"react-dom": "^16.9.0",
"react-router-dom": "^5.0.1",
"react-scripts": "^3.4.3",
"react-transition-group": "^4.3.0",
"uuid": "^3.3.3"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"jest": {
"collectCoverageFrom": [
"src/components/documentEditor/*.js",
"!<rootDir>/node_modules/",
"!<rootDir>/src/index.js",
"!<rootDir>/src/registerServiceWorker.js"
]
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"proxy": "http://localhost:5000"
}
我调查了什么
- 类似的问题似乎表明导入语句过于笼统。我找到了这篇文章
React & Jest: Cannot find module from test file。但是,我无法弄清楚我是否在帖子中专门做错了什么。
- 我还认为可能是 jest 或酶与样式库之间不兼容,但在其上找不到任何内容。
- 我在堆栈溢出时发现了这个问题,但似乎不是同一个问题Testing component created using styled component with jest and enzyme。
- 我从 page.js 中删除了 import styled from 'styled-components' 以及对样式化组件的所有引用。完成后我收到了一个新错误
src/components/documentEditor/levels/2_page/page.test.js
● Test suite failed to run
Cannot find module 'react' from 'react-beautiful-dnd.cjs.js'
However, Jest was able to find:
'./page.js'
'./page.test.js'
【问题讨论】:
标签: javascript reactjs jestjs enzyme styled-components