安裝
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