前端vue專案新增單元測試及sonar配置
阿新 • • 發佈:2021-11-22
安裝
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轉發請備註出處
【公眾號:緗言的調調】