我有一个使用 TypeScript、Jest、Webpack 和 Babel 构建的 React 应用程序(不使用 Create React App)。尝试运行“yarn jest”时,出现以下错误:

我尝试删除所有软件包并重新添加它们。它没有解决这个问题。我看过类似的问题和文档,但仍然误解了一些东西。我什至按照另一个指南从头开始设置这个环境,但我的代码仍然收到这个问题。
依赖包括...
"dependencies": {
"@babel/plugin-transform-runtime": "^7.6.2",
"@babel/polyfill": "^7.6.0",
"babel-jest": "^24.9.0",
"react": "^16.8.6",
"react-dom": "^16.8.6",
"react-test-renderer": "^16.11.0",
"source-map-loader": "^0.2.4"
},
"devDependencies": {
"@babel/core": "^7.6.0",
"@babel/preset-env": "^7.6.0",
"@babel/preset-react": "^7.0.0",
"@types/enzyme": "^3.9.2",
"@types/enzyme-adapter-react-16": "^1.0.5",
"@types/jest": "^24.0.13",
Run Code Online (Sandbox Code Playgroud)
组件的导入行...
import * as React from "react";
import { BrowserRouter as Router, Route, Switch } from "react-router-dom";
import HomePage from "./components/pages";
import {
Footer,
Header,
Navigation,
} from "./components/shared";
Run Code Online (Sandbox Code Playgroud)
测试文件....
import * as React from "react"; …Run Code Online (Sandbox Code Playgroud) SyntaxError: Cannot use import statement outside a module无论我尝试过什么,我都无法摆脱这个错误,这让我非常沮丧。有大佬解决了这个问题吗?我已经阅读了一百万个 stackoverflow 和 github 问题线程。没有明确的解决方案。
这是一个 React、Typescript、Webpack 项目。我正在尝试测试一个模块。但 Jest 不会改变以某种方式模块为普通的 javascript。
/Users/me/dev/Project/project/node_modules/variables/src/variables.js:12
import './main.js';
^^^^^^
SyntaxError: Cannot use import statement outside a module
17 |
18 | */
> 19 | import { GlobalVars } from 'variables'
| ^
20 |
21 | export const Vars = new GlobalVars()
22 |
Run Code Online (Sandbox Code Playgroud)
使用env设置babel.config:env.test.preset: ['@babel/plugin-transform-modules-commonjs']
修改transformJest 配置中的设置'^.+\\.jsx?$': 'babel-jest', '^.+\\.tsx?$': …
我在jest:24.9.0没有任何配置的情况下使用,从 create-react-app 全局安装。在这些文件中,我使用了 es6 模块。使用时没有错误"test": "react-scripts test"
但是,当我开始使用jestwith 时,"test": "jest --config jest.config.js",我看到以下错误。
FAIL src/configuration/notifications.test.js
? Test suite failed to run
/var/www/management/node/src/configuration/notifications.test.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import notifications from './notifications';
^^^^^^
SyntaxError: Cannot use import statement outside a module
Run Code Online (Sandbox Code Playgroud)