1. 安装依赖
npm install babel-jest@29.3.1
npm install @vue/cli-plugin-unit-jest@4.4.4
npm install jest-sonar-reporter@2.0.0
npm install babel-plugin-transform-require-context@0.1.1
2. 配置文件
在项目根目录增加jest.config.js配置文件,具体内容如下:
module.exports = {
moduleFileExtensions: ['js', 'json', 'vue'],
transform: {
'^.+\\.vue$': 'vue-jest',
'.+\\.(css|styl|less|sass|scss|svg|png|jpg|ttf|woff|woff2)$':
'jest-transform-stub',
'^.+\\.jsx?$': 'babel-jest'
},
moduleNameMapper: {
'^@/(.*)$': '<rootDir>/src/$1'
},
snapshotSerializers: ['jest-serializer-vue'], // 将保存的快照测试结果进行序列化
testMatch: [
'**/tests/unit/**/*.spec.(js|jsx|ts|tsx)|**/__tests__/*.(js|jsx|ts|tsx)'
], //匹配哪些文件进行测试
// collectCoverage: true,
collectCoverageFrom: ['src/utils/**/*.{js,vue}', '!src/utils/auth.js', '!src/utils/request.js', 'src/components/**/*.{js,vue}'],
coveragePathIgnorePatterns: ['/node_modules/', '/__tests__/'], // 不需要写单元测试的文件
coverageReporters: [
'lcov',
'text-summary'
],
testResultsProcessor: 'jest-sonar-reporter',
testEnvironmentOptions: {
url: "http://localhost/"
},
}
更新babel.config.js文件,添加test配置
// babel.config.js
// 解决require.context is not a function问题
module.exports = {
presets: [
'@vue/cli-plugin-babel/preset'
],
'env': {
'development': {
'plugins': ['dynamic-import-node']
},
"test": {
"plugins": ["transform-require-context"]
}
}
}
修改.gitignore文件
.DS_Store
node_modules/
dist/
npm-debug.log*
yarn-debug.log*
yarn-error.log*
coverage/
test-report.xml
# Editor directories and files
.idea
.vscode
*.suo
*.ntvs*
*.njsproj
*.sln
3.执行单元测试
在package.json script中添加启动命令,
"test:unit": "vue-cli-service test:unit --coverage"
这一步下去会生成两个文件,前提是你有写单测文件 .spec.js 文件就是单测文件
生成的两个文件一个是coverage文件夹,一个是test-report.xml 文件
前端接入sonar
根目录添加 .gitlab-ci.yml、 sonar-project.properties 配置文件
.gitlab-ci.yml
stages:
- sonar
test:
stage: sonar
tags:
- javascript
script:
- npm install
- npm run test:unit
- sonar-scanner -Dproject.settings=./sonar-project.properties -Dsonar.projectKey=$CI_PROJECT_NAME:$CI_COMMIT_BRANCH -Dsonar.projectName=$CI_PROJECT_NAME:$CI_COMMIT_BRANCH
when: always
sonar-project.properties
sonar.language=js
sonar.sources=src
sonar.sourceEncoding=UTF-8
sonar.testExecutionReportPaths=test-report.xml
sonar.javascript.lcov.reportPaths=coverage/lcov.info