作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我想在 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 配置,但到目前为止没有成功。
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/
我是一名优秀的程序员,十分优秀!