Jat*_*tra 6 javascript node.js jestjs babel-jest
我想在 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.
Run Code Online (Sandbox Code Playgroud)
我什至尝试根据文档和其他 GitHub 问题更改 Jest 配置,但到目前为止没有成功。
下面是我的 math.mjs 测试文件
const calc = (total, tippercent) => {
const tip = total * tippercent;
return total + tip;
}
export default calc
Run Code Online (Sandbox Code Playgroud)
这是我的 math.test.js
import calc from "../src/math.mjs";
test("to calculate tipercent", () => {});
Run Code Online (Sandbox Code Playgroud)
我们如何配置 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"]
}
Run Code Online (Sandbox Code Playgroud)
和 babel 配置babel.config.js:
const presets = [
[
"@babel/preset-env",
]
];
module.exports = { presets };
Run Code Online (Sandbox Code Playgroud)
最后你的脚本来运行测试package.json:
"test": "jest --config=jest.config.js",
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2565 次 |
| 最近记录: |