安装
npm install --save-dev jest @vue/test-utils
详情查看:https://vue-test-utils.vuejs.org/zh/
安装依赖:
"@vue/cli-plugin-babel": "~4.3.0",
"@vue/cli-plugin-eslint": "~4.3.0",
"@vue/cli-plugin-router": "~4.3.0",
"@vue/cli-plugin-unit-jest": "~4.3.0",
"babel-jest": "23.6.0",
"jest": "^26.6.3",
"jest-sonar-reporter": "^2.0.0",
"jest-watch-typeahead": "^0.6.1",
安装后查看本地文件夹:
.eslintrc.js文件内容:
module.exports = { env: { jest: true } }
setup.js文件内容:
import Vue from 'vue' import ElementUI from 'element-ui' Vue.use(ElementUI)
jest.config.js文件内容:配置jest.config.js使用https://jestjs.io/docs/configuration
module.exports = { moduleFileExtensions: ['js', 'jsx', 'json', 'vue'], transform: { '^.+\\.vue$': 'vue-jest', '.+\\.(css|styl|less|sass|scss|svg|png|jpg|ttf|woff|woff2)$': 'jest-transform-stub', '.*\\.(js)$': 'babel-jest' }, moduleNameMapper: { '^@/(.*)$': '<rootDir>/src/$1', '\\.(css|less)$': 'identity-obj-proxy'// 解析css文件异常处理方式 }, snapshotSerializers: ['jest-serializer-vue'], testMatch: [ '**/tests/unit/**/*.spec.(js|jsx|ts|tsx)|**/__tests__/*.(js|jsx|ts|tsx)' ], collectCoverageFrom: [ 'src/utils/**/*.{js,vue}', '!src/utils/auth.js', '!src/utils/request.js', 'src/components/**/*.{js,vue}', 'src/views/**/*.{js,vue}', '!src/views/login/**/*.{js,vue}', '!src/views/iframe/**/*.{js,vue}' ], coverageDirectory: '<rootDir>/tests/unit/coverage', 'collectCoverage': true, 'coverageReporters': [ 'lcov', 'text-summary' ], testURL: 'http://localhost/', testResultsProcessor: 'jest-sonar-reporter', setupFiles: ['./tests/setup.js'], watchPlugins: [ 'jest-watch-typeahead/filename', 'jest-watch-typeahead/testname' ] }
项目根目录下新增文件sonar-project.properties,内容如下。可以将测试结果上报给sonar
#根据具体项目修改 sonar.projectKey= **查看jenkins中配置** #根据具体项目修改 sonar.projectName= **查看jenkins中配置** # Source sonar.sources=src # Where to find tests file, also src sonar.tests=tests # But we get specific here # We don't need to exclude it in sonar.sources because it is automatically taken care of # sonar.test.inclusions=src/**/*.spec.js,src/**/*.spec.jsx,src/**/*.test.js,src/**/*.test.jsx sonar.test.inclusions=**/*tests*/** sonar.exclusions=**/*tests*/** sonar.javascript.file.suffixes=.js,.jsx,.vue # Now specify path of lcov and testlog sonar.javascript.lcov.reportPaths=tests/unit/coverage/lcov.info