我有一个使用 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 来运行我得到的测试
测试套件运行失败
...node_modules\p-retry\index.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){import retry from 'retry';
^^^^^^
SyntaxError: Cannot use import statement outside a module
> 1 | import pRetry from 'p-retry';
| ^
2 |
3 | export function Retry(tries: number) {
at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1728:14)
at Object.<anonymous> (src/common/Retry.ts:1:1)
Run Code Online (Sandbox Code Playgroud)
同时,我的 webpack 构建与 typescript 和 babel 配合得很好。我尝试了很多东西(见下文以使其工作,但到目前为止没有成功 - 并且还没有真正能够理解发生了什么。从我的角度来看 - 尽管转译的东西到目前为止对我来说是一个黑色区域我尝试让 Jest 使用 ESModules 并提供代码,并尝试提供 commonJS 模块代码。
因此,我正在寻找其他选择和方法来进一步调查。特别是一件事让我感到奇怪:错误中的 Retry.ts 文件是我的文件之一,它导入 pRetry (以 ESModule 风格编写的 node_module ),它在其代码中从“retry”(另一个节点模块)导入重试以 commonJS 风格编写)从错误的第一行开始。
所以在我看来,pRetry 并不是从它的 ESModule 代码转换而来(pRetry 的源代码以 import retry from 'retry'; 开始),而只是包装在一些 …