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

时间:2020-11-11 21:20:18

标签: node.js jestjs

我正在尝试使用Jest开始测试,但是我无法使用“导入”,那么如何在Jest中使用导入?

plus.js

function addTwo(num) {
    return num + 2;
}

export { addTwo };

test.js

import { addTwo } from './plus';

test('adds 1 + 2 to equal 3', () => {
    expect(addTwo(4)).toBe(6);
});

错误:

error ocurred

我的package.json:

{
"name": "...",
"version": "1.0.0",
"title": "...",
"homepage": "http://...",
"devDependencies": {
    "@babel/core": "7.12.3",
    "babel-loader": "8.1.0",
    "btoa": "1.2.1",
    "chalk": "3.0.0",
    "circular-dependency-plugin": "5.2.0",
    "css-loader": "5.0.0",
    "dp-grunt-contrib-copy": "0.4.4",
    "eslint": "5.16.0",
    "eslint-loader": "4.0.2",
    "file-loader": "6.2.0",
    "filemanager-plugin": "2.5.2",
    "generate-json-webpack-plugin": "2.0.0",
    "grunt": "1.1.0",
    "grunt-contrib-clean": "0.7.0",
    "grunt-contrib-compress": "1.6.0",
    "grunt-contrib-concat": "1.0.1",
    "grunt-contrib-copy": "1.0.0",
    "grunt-contrib-cssmin": "1.0.2",
    "grunt-cssjoin": "0.3.0",
    "grunt-eslint": "21.1.0",
    "grunt-exec": "3.0.0",
    "grunt-jsmin-sourcemap": "1.10.0",
    "grunt-terser": "0.1.0",
    "grunt-writefile": "0.1.4",
    "html-loader": "1.3.2",
    "jest": "^26.6.3",
    "jwt-decode": "3.0.0",
    "mini-css-extract-plugin": "1.2.1",
    "npm-run-all": "4.1.5",
    "prettier": "2.1.2",
    "prettier-webpack-plugin": "1.2.0",
    "resize-observer-polyfill": "1.5.1",
    "sass": "1.25.0",
    "sass-loader": "10.0.4",
    "sha1": "1.1.1",
    "ssh2": "0.8.9",
    "style-loader": "2.0.0",
    "vue-virtual-scroller": "1.0.10",
    "webpack": "5.3.1",
    "webpack-cli": "3.3.12",
    "xmlhttprequest": "1.8.0"
},
"dependencies": {
    "inputmask": "5.0.0",
    "jquery": "2.1.3",
    "requirejs": "2.3.6",
    "vue": "2.6.10",
    "vue-i18n": "8.15.3",
    "vuedraggable": "2.23.2"
},
"scripts": {
    "build": "npm run dev && bash ./build.sh",
    "lint": "npx eslint --fix --quiet .",
    "prettier": "npx prettier --config ./.prettierrc.json --write ./**/*.{scss,js}",
    "prod": "node node/compiler.js prod",
    "dev": "node node/compiler.js dev",
    "backup-log": "node node/logger.js",
    "test": "jest"
}
}

1 个答案:

答案 0 :(得分:0)

解决方案是安装 @ babel / preset-env

npm install --save-dev @babel/preset-env

创建文件babel.config.js

module.exports = {
    presets: [['@babel/preset-env', {targets: {node: 'current'}}]],
};