vue.js - 如何配置通过 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
。无论我运行jest
或npm 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 配置错误的问题吗?缺少一些装载机?
项目中没有 webpack 配置文件,因为它是用 vue cli 启动的。一个人声称实际配置在
node_modules/@vue/cli-service/webpack.config.js
其中并没有那么有用:// this file is for cases where we need to access the // webpack config as a file when using CLI commands. let service = process.VUE_CLI_SERVICE if (!service || process.env.VUE_CLI_API_MODE) { const Service = require('./lib/Service') service = new Service(process.env.VUE_CLI_CONTEXT || process.cwd()) service.init(process.env.VUE_CLI_MODE || process.env.NODE_ENV) } module.exports = service.resolveWebpackConfig()
(resolveWebpackConfig 好像是这个)
据我了解,调整内部 webpack 配置是在 vue.config.js 中完成的,但我不知道这是开始修改的初始配置,实际上应该调整什么
我已经尝试过
npm i babel-jest
(不确定它是否已经由 vue cli 安装),添加类似于有类似问题的人.babelrc
所做的,尝试将其他人从该线程建议的部分添加到 vue.config.js:{ "presets": ["latest"] }
configureWebpack: { module: { rules: [ { loader: "babel-loader", options: { presets: ["latest"] } } ] } },
还有一些来自这里的建议,现在我没有想法
下面你可以看到所有的配置文件
一个好处:如果我将 Paginator.spec.js 重命名为 Paginator.spec.ts 会使 Jest 显示这个:
● Test suite failed to run Passing cached plugin instances is not supported in babel.loadPartialConfig() at forEach.item (node_modules/@babel/core/lib/config/partial.js:120:13) at Array.forEach (<anonymous>) at loadPartialConfig (node_modules/@babel/core/lib/config/partial.js:118:27) at TsJestTransformer.process (node_modules/ts-jest/dist/ts-jest-transformer.js:110:32)
谁能建议如何修复配置?或者如何调试?从我目前所读到的内容来看,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"
]
}
解决方案
推荐阅读
- javascript - 命令被忽略。未知目标:使用 Lit-Element 时未定义
- c# - 扩展 LayoutAnchorable 以使用自己的样式
- sql - 在 SQL 中,我如何对一长串列中的每一个进行分组并获取计数,并将它们全部组合到一个表中?
- python - 遍历文件夹,提取文本,创建单个 df
- python - Pandas -> GroupBy 两列将大小添加为第三
- laravel-5 - 什么时候
.queued 被解雇? - javascript - 使用 setTimeout() 显示 react-native-modal
- python - 如何使用正则表达式仅匹配 Python 中的一个字符?
- segmentation-fault - 当我尝试进行平面模型分割时,pcl 代码中的“分割错误(核心转储)”
- postgresql - Postgres:更新 JSON 数组并删除与键匹配的元素