代码之家  ›  专栏  ›  技术社区  ›  AnchovyLegend

单元测试Vue组件-Jest设置-意外的标识符错误

  •  5
  • AnchovyLegend  · 技术社区  · 7 年前

    在运行测试套件时,Jest成功地找到了我要测试的文件,并在第1行生成了以下意外的标识符错误消息。 知道为什么吗?少了什么吗?我已经试着解决这个问题很长时间了。

    /Users/foo/Sites/test/Test.spec.js:1
        ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import Test from './Test.vue';
                                                                                                        ^^^^
    
        SyntaxError: Unexpected identifier
    
          at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/script_transformer.js:403:17)
    

    注意,删除import语句将成功运行测试。然而,我设置Jest的全部原因是为了测试vue组件。

    <template>
            <div class="test">
            </div>
    </template>
    
    <script>
        export default {
            name: 'test',
            components: { },
            data() {
                return {
    
                }
            },
            methods: {
                helloWorld() {
                    return 'hello world';
                }
            }
        }
    </script>
    

    测试规范js

    import Test from './Test.vue'
    
    describe('Test',() => {
       it('test', () => {
         expect(true).toBe(true);
       });
    });
    

    "devDependencies": {
        "@vue/test-utils": "^1.0.0-beta.25",
        "axios": "^0.18.0",
        "babel-core": "^6.26.0",
        "babel-jest": "^23.6.0",
        "babel-loader": "^7.1.2",
        "cross-env": "^5.1.1",
        "file-loader": "^2.0.0",
        "jest": "^23.6.0",
        "jquery": "^3.2",
        "laravel-mix": "^2.0",
        "lodash": "^4.17.4",
        "popper.js": "^1.14.3",
        "source-map-support": "^0.5.9",
        "vue": "^2.5.7",
        "vue-jest": "^3.0.0",
        "vue-test-utils": "^1.0.0-beta.11",
        "webpack": "^3.8.1"
      },
      "jest": {
        "moduleFileExtensions": [
          "js",
          "json",
          "vue"
        ],
        "transform": {
          ".*\\.(vue)$": "vue-jest",
          "^.+\\.js$": "babel-jest"
        }
      }
    
    1 回复  |  直到 7 年前
        1
  •  2
  •   Stamatios Stamoulas    7 年前

    您在测试中使用的是ES6特性,即import语句,因此需要使用预设将它们编译为ES5。

    @babel/preset-env ,就像这样,

    //babel.config.js
    module.exports = {
      presets: ["@babel/preset-env"]
    };
    

    接下来,在jest设置下的package.json中,让jest知道 root 测试代码的 module directories 会被jest递归搜索,就像这样,

    //package.json
    "roots": [
      "test"
    ],
    "moduleDirectories": [
      "test",
      "node_modules"
    ],