首页 > 解决方案 > 如何配置通过 Vue cli 3 添加到应用程序的 Jest?

问题描述

我正在尝试将使用 Jest 的测试引入使用 Vue 构建的应用程序中。我跑了

vue add unit-jest

与使用 Jest 指南测试单个文件组件的建议类似,创建了以下简单的测试文件(Paginator.spec.js 与 Paginator.vue 在同一文件夹中,即/src/components):

import { mount } from '@vue/test-utils'
import Paginator from "./Paginator.vue";

describe('Paginator', () => {
    it('is a Vue instance', () => {
        const wrapper = mount(Paginator);
        // const a = 2;
        expect(wrapper.isVueInstance()).toBeTruthy();
        // expect(a).toBe(2);
    })
});

最初我对 Jest 本身没有找到文件有一些问题。后来我改变了 jest.config.js

testMatch: [
  '**/tests/unit/**/*.spec.(js|jsx|ts|tsx)|**/__tests__/*.(js|jsx|ts|tsx)'
],

testMatch: [
  '**/*.spec.(js|ts)|**/tests/unit/**/*.spec.(js|jsx|ts|tsx)|**/__tests__/*.(js|jsx|ts|tsx)'
],

在一些奇怪的故障之后,我找到了文件(确实git stash,确保应用程序正在运行,然后git stash pop它开始查找文件)。

但是我仍然有 Jest 无法识别的问题import。无论我运行jestnpm test(即vue-cli-service test:unit),我都会收到以下错误。像这样的简单测试正常工作:

describe('tests of components', () => {
    it('work', () => {
        const a = 2;
        expect(a).toBe(2);
    })
});

但是问题开头显示的测试带来了

测试套件无法运行
[...]

({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import { mount } from '@vue/test-utils'
                                                                                                ^
SyntaxError: Unexpected token {
  at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/script_transformer.js:403:17)

如果我将导入顺序切换为

import Paginator from "./Paginator.vue";
import { mount } from '@vue/test-utils'

我明白了

● Test suite failed to run

  C:\NNTC\medkiosk\src\components\Paginator.spec.js:1
  ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import Paginator from "./Paginator.vue";
                                                                                                  ^^^^^^^^^

  SyntaxError: Unexpected identifier

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

(除了如上所示扩展正则表达式外,我没有以任何方式更改 jest.config.js)

这里有什么问题?看起来 Jest 无法识别import为语言功能。这是 webpack 配置错误的问题吗?缺少一些装载机?

谁能建议如何修复配置?或者如何调试?从我目前所读到的内容来看,Jest 可能应该通过 babel-loader 获取一个文件,但事实并非如此,但我不确定。我知道,我可能对 Webpack 的工作原理不太了解,所以也欢迎提示学习什么,我会在找到解决方案时发布解决方案。

jest.config.js:

module.exports = {
  moduleFileExtensions: [
    'js',
    'jsx',
    'json',
    'vue',
    'ts',
    'tsx'
  ],
  transform: {
    '^.+\\.vue$': 'vue-jest',
    '.+\\.(css|styl|less|sass|scss|svg|png|jpg|ttf|woff|woff2)$': 'jest-transform-stub',
    '^.+\\.tsx?$': 'ts-jest'
  },
  transformIgnorePatterns: [
    '/node_modules/'
  ],
  moduleNameMapper: {
    '^@/(.*)$': '<rootDir>/src/$1'
  },
  snapshotSerializers: [
    'jest-serializer-vue'
  ],
  testMatch: [
    '**/*.spec.(js|ts)|**/tests/unit/**/*.spec.(js|jsx|ts|tsx)|**/__tests__/*.(js|jsx|ts|tsx)'
  ],
  testURL: 'http://localhost/',
  watchPlugins: [
    'jest-watch-typeahead/filename',
    'jest-watch-typeahead/testname'
  ],
  globals: {
    'ts-jest': {
      babelConfig: true
    }
  }
};

babel.config.js:

module.exports = {
  presets: [
    '@vue/app'
  ]
}

vue.config.js:

module.exports = {
    // the default value is '/', which may be ok for production but is not suitable for local build/deploy
    publicPath: ''
};

package.json 的一部分:

  "scripts": {
    "lint": "vue-cli-service lint",
    "serve": "vue-cli-service serve",
    "test:unit": "vue-cli-service test:unit",
    "build": "vue-cli-service build"
  },
  "dependencies": {
    "core-js": "^2.6.5",
    "vue": "^2.6.10",
    "vuex": "^3.1.1",
    "vue-class-component": "^7.0.2",
    "vue-property-decorator": "^8.2.2",
    "axios": "^0.19.0",
    // more packages
  },
  "devDependencies": {
    "@types/jest": "^23.1.4",
    "@vue/cli-plugin-babel": "^3.11.0",
    "@vue/cli-plugin-eslint": "^3.11.0",
    "@vue/cli-plugin-typescript": "^3.11.0",
    "@vue/cli-plugin-unit-jest": "^3.11.0",
    "@vue/cli-service": "^3.11.0",
    "@vue/eslint-config-typescript": "^4.0.0",
    "@vue/test-utils": "1.0.0-beta.29",
    "babel-core": "7.0.0-bridge.0",
    "babel-eslint": "^10.0.1",
    "eslint": "^5.16.0",
    "eslint-plugin-vue": "^5.0.0",
    "ts-jest": "^23.0.0",
    "typescript": "^3.4.3",
    "vue-template-compiler": "^2.6.10"
  },
  "eslintConfig": {
    "root": true,
    "env": {
      "node": true
    },
    "extends": [
      "plugin:vue/essential",
      "eslint:recommended",
      "@vue/typescript"
    ],
    "rules": {},
    "parserOptions": {
      "parser": "@typescript-eslint/parser"
    },
    "overrides": [
      {
        "files": [
          "**/__tests__/*.{j,t}s?(x)"
        ],
        "env": {
          "jest": true
        }
      }
    ]
  },
  "postcss": {
    "plugins": {
      "autoprefixer": {}
    }
  },
  "browserslist": [
    "> 1%",
    "last 2 versions"
  ]
}

tsconfig.json:

{
  "compilerOptions": {
    "target": "esnext",
    "module": "esnext",
    "strict": true,
    "jsx": "preserve",
    "importHelpers": true,
    "moduleResolution": "node",
    "experimentalDecorators": true,
    "allowJs": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "sourceMap": true,
    "baseUrl": ".",
    "types": [
      "webpack-env",
      "jest"
    ],
    "paths": {
      "@/*": [
        "src/*"
      ]
    },
    "lib": [
      "esnext",
      "dom",
      "dom.iterable",
      "scripthost"
    ]
  },
  "include": [
    "src/**/*.ts",
    "src/**/*.tsx",
    "src/**/*.vue",
    "tests/**/*.ts",
    "tests/**/*.tsx"
  ],
  "exclude": [
    "node_modules"
  ]
}

标签: vue.jswebpackjestjsbabeljsvue-cli-3

解决方案


推荐阅读