我已经设置了Jest,它可以正常运行。但是,当我为包含扩展操作符的文件创建测试时,测试套件将失败。
我正在使用通过Jest从CLI配置的Vue。
我尝试过的事情
我尝试将babel-plugin-transform-object-rest-spread
作为插件添加到babel.config.js,但这没有结果。
我还尝试将@babel/plugin-proposal-object-rest-spread
作为插件添加到babel.config.js,但这也没有结果。
babel.config.js:
module.exports = {
presets: ["@babel/preset-env", "@vue/app"]
};
package.json(笑话部分):
"jest": {
"collectCoverage": true,
"collectCoverageFrom": [
"**/*.{js,vue}",
"!**/node_modules/**"
],
"moduleFileExtensions": [
"js",
"json",
"vue"
],
"moduleNameMapper": {
"^@/(.*)$": "<rootDir>/src/$1"
},
"transform": {
"^.+\\.js?$": "<rootDir>/node_modules/babel-jest",
".*\\.(vue)$": "<rootDir>/node_modules/vue-jest"
}
}
component.spec.js:
import { shallowMount } from '@vue/test-utils';
import Component from '@/views/xx/x/Component.vue';
import Vue from 'vue';
import BootstrapVue from 'bootstrap-vue';
Vue.use(BootstrapVue);
describe('About component', () => {
let wrapper;
beforeEach(() => {
wrapper = shallowMount(Component);
});
test('is a Vue instance', () => {
expect(wrapper.isVueInstance()).toBeTruthy();
});
});
错误:
FAIL src/__tests__/views/x/Component.spec.js
● Test suite failed to run
D:\projects\project\project-frontend\node_modules\@babel\runtime-corejs2\helpers\esm\objectSpread.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import _Object$getOwnPropertyDescriptor from "../../core-js/object/get-own-property-descriptor";
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
SyntaxError: Unexpected identifier
at ScriptTransformer._transformAndBuildScript (node_modules/@jest/transform/build/ScriptTransformer.js:471:17)
at ScriptTransformer.transform (node_modules/@jest/transform/build/ScriptTransformer.js:513:25)
at src/views/xx/x/Component.vue:670:49
at Object.<anonymous> (src/views/xx/x/Component.vue:810:3)
答案 0 :(得分:0)
在package.json中 确保此插入的“ babel-core”版本最高为^ 7.0.0-0,如下所示。
“ devDependencies”:{ “ babel-core”:“ ^ 7.0.0-0” }
答案 1 :(得分:0)
对我来说,最后一步是在jest config中提供正确的env变量,以解释为什么需要它的原因here。还要确保已安装babel软件包
共享整个配置 //开玩笑
process.env.VUE_CLI_BABEL_TARGET_NODE = true;
process.env.VUE_CLI_BABEL_TRANSPILE_MODULES = true;
module.exports = {
verbose: true,
roots: ["<rootDir>/src/", "<rootDir>/spec/"],
moduleFileExtensions: ['js', 'vue','json'],
moduleNameMapper: {
'^@/(.*)$': '<rootDir>/src/$1',
},
transform: {
"^.+\\.js$": "babel-jest",
"^.+\\.vue$": "vue-jest",
},
snapshotSerializers: [
"jest-serializer-vue"
]
}
//在json包中
"@babel/core": "^7.9.6",
"@babel/plugin-transform-runtime": "^7.9.6",
"@babel/preset-env": "^7.9.5",
"babel-core": "^7.0.0-bridge.0",
"babel-jest": "^25.4.0",