使用Jest测试vuetify组件时如何解决'SyntaxError:Unexpected identifier'

时间:2019-04-12 15:26:15

标签: vue.js jestjs vuetify.js babel-jest vue-test-utils

我在vuetify中编写了许多可重用的组件。我正在使用Jest测试框架进行单元测试。当我运行“ npm run test”时,测试失败,并显示“ SyntaxError:意外的标识符”。

我所有的babel配置和jest配置都在package.json文件中。当我创建没有任何vuetify组件的规范文件时,测试就可以了。但是一旦添加了vuetify,它就会失真。我首先使用@ vue / test-utils中的localValue来消耗vuetify。没用然后我使用了Vue.use(Vuetify),但仍然无法正常工作。

package.json

        {
      "name": "xyz",
      "version": "0.2.0",
      "private": true,
      "scripts": {
        "serve": "vue-cli-service serve",
        "build": "vue-cli-service build",
        "test": "jest",
        "clear_jest": "jest --clearCache"
      },
      "dependencies": {
        "@contentful/rich-text-html-renderer": "^13.0.0",
        "@storybook/addon-a11y": "^4.1.4",
        "avoriaz": "^6.3.0",
        "axios": "^0.18.0",
        "axios-mock-adapter": "^1.16.0",
        "contentful": "^7.3.0",
        "deepdash": "^1.9.5",
        "eslint": "^5.15.3",
        "jest": "^24.5.0",
        "jest-serializer-vue": "^2.0.2",
        "json-server": "^0.14.2",
        "lodash": "^4.17.11",
        "moment": "^2.24.0",
        "nightwatch": "^1.0.19",
        "node-sass": "^4.11.0",
        "purgecss": "^1.1.0",
        "sass-loader": "^7.1.0",
        "storybook-vue-router": "^1.0.2",
        "tailwindcss-aspect-ratio": "^1.0.1",
        "tailwindcss-gradients": "^1.1.0",
        "tailwindcss-transition": "^1.0.5",
        "vee-validate": "^2.2.2",
        "vue": "^2.5.19",
        "vue-faq-accordion": "^1.2.1",
        "vue-jest": "^3.0.4",
        "vue-router": "^3.0.2",
        "vue-template-compiler": "^2.5.20",
        "vuelidate": "^0.7.4",
        "vuetify": "^1.5.7",
        "vuex": "^3.1.0",
        "vuex-persist": "^2.0.0"
      },
      "devDependencies": {
        "@babel/core": "^7.3.4",
        "@babel/preset-env": "^7.3.4",
        "@storybook/addon-actions": "^4.1.0",
        "@storybook/addon-links": "^4.1.0",
        "@vue/cli-plugin-babel": "^3.2.0",
        "@vue/cli-plugin-eslint": "^3.2.1",
        "@vue/cli-service": "^3.2.0",
        "@vue/test-utils": "^1.0.0-beta.29",
        "babel-core": "^7.0.0-bridge.0",
        "babel-jest": "^23.6.0",
        "babel-preset-vue": "^2.0.2",
        "chromedriver": "^2.46.0",
        "concurrently": "^4.1.0",
        "cross-env": "^5.2.0",
        "cucumber": "^5.1.0",
        "cucumber-html-reporter": "^4.0.5",
        "cucumber-pretty": "^1.5.0",
        "eslint": "^5.15.3",
        "geckodriver": "^1.16.0",
        "http-server": "^0.11.1",
        "jest-transform-stub": "^2.0.0",
        "mkdirp": "^0.5.1",
        "nightwatch-api": "^2.1.3",
        "stylus": "^0.54.5",
        "stylus-loader": "^3.0.1",
        "vue-cli-plugin-storybook": "^0.5.0",
        "vue-cli-plugin-svg": "^0.1.2",
        "vue-cli-plugin-tailwind": "^0.4.0",
        "vue-cli-plugin-vuetify": "^0.5.0",
        "vue-svg-loader": "^0.11.0",
        "vue-template-compiler": "^2.5.21",
        "vuetify": "^1.5.7",
        "vuetify-loader": "^1.0.5"
      },
      "babel": {
        "presets": [
          [
            "@babel/preset-env",
            {
              "modules": "commonjs",
              "targets": {
                "node": "current"
              }
            }
          ]
        ]
      },
      "eslintConfig": {
        "root": true,
        "env": {
          "node": true
        },
        "extends": [
          "plugin:vue/essential",
          "eslint:recommended"
        ],
        "rules": {},
        "parserOptions": {
          "parser": "babel-eslint"
        }
      },
      "browserslist": [
        "> 5%",
        "last 5 versions",
        "not ie <= 10"
      ],
      "jest": {
        "moduleFileExtensions": [
          "js",
          "vue"
        ],
        "moduleNameMapper": {
          "^@/(.*)$": "<rootDir>/src/$1",
          "\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/__mocks__/fileMock.js",
          "\\.(css|less)$": "<rootDir>/__mocks__/styleMock.js"
        },
        "snapshotSerializers": [
          "<rootDir>/node_modules/jest-serializer-vue"
        ],
        "transformIgnorePatterns": [
          "<rootDir>/node_modules/(?!vuetify)"
        ],
        "transform": {
          ".*\\.(vue)$": "<rootDir>/node_modules/vue-jest",
          "^.+\\.js$": "<rootDir>/node_modules/babel-jest",
          ".+\\.(css|styl|less|sass|scss|png|jpg|ttf|woff|woff2)$": "jest-transform-stub"
        }
      }
    }

Toolbar.vue

        <template>
          <div>
            <v-toolbar class="toolbar" height="70">
              <v-toolbar-title class="toolbar-title" @click="goToHome()">{{ title }}</v-toolbar-title>
              <v-spacer></v-spacer>
              <Profile v-if="user.status"/>
            </v-toolbar>
          </div>
        </template>

        <script>
        import Profile from '@/components/Profile'
        export default {
          props: {
            title: {
              type: String,
              required: true
            }
          },
          components: {
            Profile
          },
          methods: {
            goToHome() {
              this.$router.push('/home')
            }
          }
        }
        </script>

        <style scoped lang="postcss">
        .toolbar-title {
          color: #ffffff;
          text-decoration: none;
          cursor: pointer;
        }
        .toolbar {
          @apply bg-secondary !important;
        }
        </style>

Toolbar.spec.js

    import { shallowMount } from '@vue/test-utils'
    import Toolbar from '@/components/List'
    import Vuetify from 'vuetify'
    import Vue from 'vue'

    describe('Toolbar.vue', () => {
        let wrp
        beforeEach(() => {
            Vue.use(Vuetify)
            wrp = shallowMount(Toolbar)
        })

        it('Toolbar is a vue instance', () => {
            expect(wrp.isVueInstance()).toBeTruthy()
        })
    })

期望的结果应该是:

    > jest

     PASS  test/unit/component/Toolbar.spec.js
      Toolbar.vue
        √ Toolbar is a vue instance (21ms)

    Test Suites: 1 passed, 1 total
    Tests:       1 passed, 1 total
    Snapshots:   0 total
    Time:        4.882s
    Ran all test suites.

实际:         C:\ rahul13615> npm运行测试

    > myproject@0.2.0 test C:\rahul13615\
    > jest

     FAIL  test/unit/component/Toolbar.spec.js
      ● Test suite failed to run

        C:\rahul13615\node_modules\@babel\runtime-corejs2\helpers\esm\typeof.js:1
        ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import _Symbol$iterator from "../../core-js/symbol/iterator";
                                                                                                        ^^^^^^^^^^^^^^^^

        SyntaxError: Unexpected identifier

          at ScriptTransformer._transformAndBuildScript (node_modules/@jest/transform/build/ScriptTransformer.js:451:17)
          at ScriptTransformer.transform (node_modules/@jest/transform/build/ScriptTransformer.js:493:19)
          at Object.<anonymous> (node_modules/vuetify/dist/vuetify.js:91:39)

    Test Suites: 1 failed, 1 total
    Tests:       0 total
    Snapshots:   0 total
    Time:        6.328s
    Ran all test suites.
    npm ERR! code ELIFECYCLE
    npm ERR! errno 1
    npm ERR! myproject@0.2.0 test: `jest`
    npm ERR! Exit status 1
    npm ERR!
    npm ERR! Failed at the myproject@0.2.0 test script.
    npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

    npm ERR! A complete log of this run can be found in:

2 个答案:

答案 0 :(得分:0)

重新启动计算机。 我不骗你,我有同样的错误,尝试解决了2天。完全重新启动系统即可解决该问题。

答案 1 :(得分:0)

@barakbd实际上是正确的,不知道为什么他的答案被否决了。

您可以先尝试使用import pandas as pd import glob import os import numpy as np path = './' #column = ['20201-2.0'] # all_files = glob.glob(path + "/*.csv") #li = [] all_files = os.listdir(path) all_df = pd.DataFrame() for filename in all_files: if not filename.endswith('csv'): continue print('extracting info from ' + filename) # Option 1 below worked, although without isolating the non-nulled values # 1. df = pd.read_csv(filename, encoding="ISO-8859-1") df = pd.read_csv(filename, header=0) #df = df[df['20201-2.0'].notnull()] df_subset = df.dropna(subset=['20201-2.0']) print('processed ' + filename) # You can now export all outcomes in new csv files file_name = filename.split('.')[0] + '_new' + '.csv' print('saving to' + file_name) export_csv = df_subset.to_csv('./' + file_name, index=None) del df del export_csv 手动清除缓存,如果这样做不起作用,则重新启动应该会有所帮助,这似乎可以清除另一个也影响了笑话的缓存。

重新启动为我解决了这个问题。