gpt4 book ai didi

javascript - 如何在 Jest 的 xyz.test.js 中导入 ".mjs"模块?

转载 作者:行者123 更新时间:2023-12-03 12:17:25 26 4
gpt4 key购买 nike

我想在 Jest 26.1.0 中使用 ES6 模块的导入/导出功能(因为我的整个项目都使用它)。
我为我的测试用例创建了一个名为 testCases/ 的目录其中包含 math.mjs文件。现在我正在尝试将这个文件导入 math.test.js (开 Jest )。每当我运行 npm run test ,它会引发以下错误。

>Details:

/home/jatin/Downloads/Node.js/task-manager-app/TestCases/math.test.js:1
import calc from "../src/math.mjs";
^^^^^^

SyntaxError: Cannot use import statement outside a module

at Runtime._execModule (node_modules/jest-runtime/build/index.js:1179:56)

Test Suites: 1 failed, 1 total
Tests: 0 total
Snapshots: 0 total
Time: 1.556 s
Ran all test suites.
npm ERR! Test failed. See above for more details.
我什至尝试根据文档和其他 GitHub 问题更改 Jest 配置,但到目前为止没有成功。
下面是我的 math.mjs 测试文件
  const calc = (total, tippercent) => {
const tip = total * tippercent;
return total + tip;
}

export default calc
这是我的 math.test.js
import calc from "../src/math.mjs";

test("to calculate tipercent", () => {});
我们如何配置 Jest 来解析 .mjs 模块?

最佳答案

我认为它适用于以下设置:
在您的应用程序的根级别,jest.config.js :

module.exports = {
testRegex: "(/__tests__/.*|(\\.|/)(test|spec))\\.(jsx?|js?|tsx?|ts?)$",
transform: {
"^.+\\.jsx?$": "babel-jest",
"^.+\\.mjs$": "babel-jest",
},
testPathIgnorePatterns: ["<rootDir>/build/", "<rootDir>/node_modules/"],
moduleFileExtensions: ["js", "jsx", "mjs"]
}

和 babel 配置 babel.config.js :
const presets = [
[
"@babel/preset-env",
]
];

module.exports = { presets };

最后是您在 package.json 中运行测试的脚本:
"test": "jest --config=jest.config.js",

关于javascript - 如何在 Jest 的 xyz.test.js 中导入 ".mjs"模块?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63114333/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com