Node:无法在 Jest 中的模块外部使用 import 语句

问题描述 投票:0回答:1

直到今天我已经用 jest 做了很多测试,但从未收到过这个错误。我还没有更新我的 Jest 版本,代码和其他日子一样。

收到的错误是:

josecarlos@R2D2 ~/Workspace/BlueCode/Youmalou/Backend [add/Memcached-2*]$ npx jest ./unittest/memcached.test.js

Jest encountered an unexpected token

Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.

Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration.

**By default "node_modules" folder is ignored by transformers.**

Details:

/home/josecarlos/Workspace/BlueCode/Youmalou/Backend/node_modules/axios/index.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){import axios from './lib/axios.js';
                                                                                  ^^^^^^

SyntaxError: Cannot use import statement outside a module

  1 | import config from "../config";
> 2 | import axios from "axios";
    | ^
  3 | import {Result} from "./result";
  4 | import {PGMappingDDBB} from "../database/postgresql/pg_mapping";
  5 | import {PGBackendDDBB} from "../database/postgresql/pg_backend";

  at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1728:14)
  at Object.<anonymous> (com/functions.js:2:1)

axios 模块已正确导入,该模块位于 node_modules 中,以及收到的消息中的说法 默认情况下,“node_modules”文件夹会被转换器忽略。

我的 .babelrc 是:

{
   "presets": ["@babel/preset-env"],
   "plugins": ["@babel/plugin-transform-runtime"
   ]  
}

如果我将 "type": "module" 添加到我的 package.json 中,它将不起作用。

当我尝试运行测试时,我使用以下命令进行操作:npx jest ./unittest/memcached.test.js以及我所说的直到昨天为止都没有任何问题,但今天不起作用。

那么,我该如何修复这个错误呢?

编辑我

我已经安装了“babel-jest”:“^29.7.0”并使用以下代码创建文件 jest.config.js:

module.exports = {
    transform: {
      '^.+\\.jsx?$': 'babel-jest',
    },
    transformIgnorePatterns: ["/node_modules/"]
};

而且这不起作用。我收到同样的错误!

node.js axios jestjs
1个回答
0
投票

我已经解决了我的问题。我已将 Jest 版本更新到最新版本。现在,我已经安装了 29.7.0 版本的 Jest。

© www.soinside.com 2019 - 2024. All rights reserved.