如何修复从'vue'导入错误Vue导致SyntaxError:意外标识符

时间:2019-02-06 11:58:56

标签: unit-testing vue.js jestjs

我正在尝试为我正在研究的Vue.js项目设置测试框架。我试图为此使用Jest,但最终出现错误,但似乎没有找到解决方案。当我尝试运行测试时,在终端中出现语法错误。

我得到的错误是:

Test suite failed to run

Import Vue from 'vue';

       ^^^

SyntaxError: Unexpected identifier"
  at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/script_transformer.js:403:17) 

我一直在环顾四周,但找不到能帮助我的解决方案。 删除导入的Vue时,测试通过。

我通过命令npm run tests

运行测试
// package.json
{
  "name": "mlink-pwa",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "serve": "vue-cli-service serve",
    "build": "vue-cli-service build",
    "lint": "vue-cli-service lint",
    "tests": "NODE_ENV=testing vue-cli-service test:unit"
  },
  "dependencies": {
    "chart.js": "^2.7.3",
    "chartjs-plugin-labels": "^1.1.0",
    "countup.js": "^1.9.3",
    "dexie": "^2.0.4",
    "gauge-chart": "^0.4.3",
    "moment": "^2.22.2",
    "progressbar.js": "^1.0.1",
    "raven-js": "^3.27.0",
    "register-service-worker": "^1.5.2",
    "vue": "^2.5.17",
    "vue-countup-v2": "^2.0.0",
    "vue-i18n": "^8.3.2",
    "vue-router": "^3.0.2",
    "vuedraggable": "^2.16.0",
    "vuelidate": "^0.7.4",
    "vuex": "^3.0.1"
  },
  "devDependencies": {
    "@babel/preset-env": "^7.3.1",
    "@vue/cli": "^3.1.3",
    "@vue/cli-plugin-babel": "^3.1.1",
    "@vue/cli-plugin-e2e-nightwatch": "^3.4.0",
    "@vue/cli-plugin-eslint": "^3.1.5",
    "@vue/cli-plugin-pwa": "^3.1.2",
    "@vue/cli-plugin-unit-jest": "^3.4.0",
    "@vue/cli-service": "^3.1.4",
    "@vue/eslint-config-standard": "^4.0.0",
    "@vue/test-utils": "^1.0.0-beta.25",
    "babel": "^6.23.0",
    "babel-core": "7.0.0-bridge.0",
    "babel-jest": "^24.1.0",
    "babel-plugin-transform-es2015-modules-commonjs": "^6.26.2",
    "eslint-plugin-jasmine": "^2.10.1",
    "jasmine": "^3.3.1",
    "node-sass": "^4.10.0",
    "sass-loader": "^7.1.0",
    "vue-jest": "^3.0.2",
    "vue-template-compiler": "^2.5.17"
  }
}

// jest.config.js
module.exports = {
    moduleFileExtensions: ['js', 'json', 'vue'],
    transform: {
        '^.+\\.jsx?$': 'babel-jest',
        '^.+\\.vue$': 'vue-jest'
    },
  clearMocks: true,
  coverageDirectory: "coverage",
};

// babel.config.js
module.exports = {
  env: {
    testing: {
      presets: [
        ['env', { modules: false }], 
        '@babel/preset-env',
        '@vue/app'
      ],
      plugins: [
        'transform-es2015-modules-commonjs'
     ]
    }
  }
 }

// first.spec.js - THIS FAILS
import Vue from 'vue'

describe('', () => {  
    it('first test', () => {
        expect(true).toEqual(true);
    });
});

// first.spec.js - THIS PASSES
describe('', () => {  
    it('first test', () => {
        expect(true).toEqual(true);
    });
});

预期: 我希望测试套件能够运行并且测试能够通过。

实际: 测试套件无法运行。

1 个答案:

答案 0 :(得分:0)

这是特定版本的vue-cli的问题。安装最新版本并启动新项目可以解决此问题。或者在“模拟”项目中执行此操作,然后将所有npm依赖项版本复制到现有项目中。