@ttvuong/code-coverage
Version:
Comprehensive code coverage measurement and reporting tool for TypeScript and JavaScript projects
430 lines (318 loc) • 12.7 kB
Markdown
# @hemidi/code-coverage
> Công cụ đo lường và báo cáo độ bao phủ mã nguồn cho dự án TypeScript/JavaScript.
## Giới thiệu
`@hemidi/code-coverage` là một công cụ để đo lường, phân tích và báo cáo độ bao phủ mã nguồn trong dự án. Được xây dựng trên nền tảng Jest và Istanbul, package cung cấp nhiều định dạng báo cáo, kiểm tra ngưỡng và khả năng tích hợp CI/CD.
### Tính năng chính
- **Multiple Report Formats**: Hỗ trợ HTML, JSON, LCOV, Cobertura, text reports
- **Threshold Enforcement**: Kiểm tra ngưỡng coverage cho CI/CD pipelines
- **Coverage Merging**: Gộp nhiều báo cáo coverage từ các test runs
- **CI/CD Ready**: Tối ưu cho môi trường continuous integration
- **TypeScript Support**: Hỗ trợ đầy đủ cho TypeScript projects
- **Beautiful Reports**: Báo cáo HTML tương tác với visualization chi tiết
- **Fast & Efficient**: Tận dụng Jest parallel test execution
- **Auto-initialization**: Tự động setup coverage configurations
## Cài đặt
```bash
npm i -D @hemidi/code-coverage jest istanbul-lib-coverage
```
## Bắt đầu nhanh
### Bước 1: Khởi tạo project
```bash
npx midi-cov init
```
Lệnh này sẽ:
- Thêm coverage scripts vào package.json
- Cấu hình Jest coverage settings mặc định
- Thiết lập coverage thresholds
### Bước 2: Chạy phân tích coverage
```bash
npm run coverage
```
### Bước 3: Kiểm tra ngưỡng coverage
```bash
npm run coverage:check # Kiểm tra với ngưỡng mặc định
npm run coverage:ci # Chạy trong CI mode
```
## Tham chiếu Scripts
### Scripts cơ bản
| Script | Mô tả | Mode | Output |
| ----------------- | ---------------------------------- | ---- | ---------------- |
| `coverage` | Phân tích coverage với HTML report | dev | HTML + Console |
| `coverage:ci` | Chạy coverage trong CI mode | ci | JSON + LCOV |
| `coverage:watch` | Chạy coverage với watch mode | dev | Console |
| `coverage:report` | Tạo comprehensive reports | dev | HTML + Cobertura |
| `coverage:check` | Kiểm tra coverage với thresholds | ci | Pass/Fail |
| `coverage:merge` | Gộp nhiều coverage reports | - | Merged JSON |
### Scripts được tạo tự động
Khi chạy `npx midi-cov init`, các scripts sau sẽ được thêm vào `package.json`:
```json
{
"scripts": {
"coverage": "midi-cov --dev --report-html ./coverage/index.html --report-text",
"coverage:ci": "midi-cov --ci --report-json ./coverage/coverage.json --report-lcov ./coverage/lcov.info",
"coverage:watch": "midi-cov --dev --watch --report-text",
"coverage:report": "midi-cov --dev --report-html ./coverage/index.html --report-cobertura ./coverage/cobertura-coverage.xml",
"coverage:check": "midi-cov --ci --threshold-global 80 --threshold-lines 80 --threshold-functions 80 --threshold-branches 75",
"coverage:merge": "midi-cov merge \"coverage/*.json\" --merge-output ./coverage/merged-coverage.json"
}
}
```
## Options tham số
### Tùy chọn Mode
| Option | Mô tả | Default | Mục đích |
| -------- | ------------------------- | ------- | ----------------- |
| `--ci` | Chạy ở chế độ CI | false | CI/CD integration |
| `--dev` | Chạy ở chế độ development | true | Local development |
| `--init` | Khởi tạo project | false | Setup project |
| `--help` | Hiển thị trợ giúp | false | Documentation |
### Tùy chọn Report
| Option | Mô tả | Default | Format |
| --------------------------- | -------------------------- | ------- | ---------- |
| `--report-json <path>` | Xuất báo cáo JSON | - | JSON |
| `--report-html <path>` | Xuất báo cáo HTML | - | HTML |
| `--report-lcov <path>` | Xuất báo cáo LCOV | - | LCOV |
| `--report-cobertura <path>` | Xuất báo cáo Cobertura XML | - | XML |
| `--report-text` | Hiển thị báo cáo console | false | Plain text |
### Tùy chọn Threshold
| Option | Mô tả | Default | Ví dụ |
| ---------------------------- | ------------------------------- | ------- | --------------------------- |
| `--threshold-statements <n>` | Ngưỡng tối thiểu cho statements | - | `--threshold-statements 80` |
| `--threshold-branches <n>` | Ngưỡng tối thiểu cho branches | - | `--threshold-branches 75` |
| `--threshold-functions <n>` | Ngưỡng tối thiểu cho functions | - | `--threshold-functions 80` |
| `--threshold-lines <n>` | Ngưỡng tối thiểu cho lines | - | `--threshold-lines 85` |
| `--threshold-global <n>` | Ngưỡng tối thiểu chung | - | `--threshold-global 80` |
### Tùy chọn Configuration
| Option | Mô tả | Default | Format |
| ---------------------- | ---------------------------- | ------------- | ------- |
| `--config <path>` | Đường dẫn file cấu hình Jest | Auto-discover | Path |
| `--max-workers <n>` | Số lượng worker processes | Auto | Number |
| `--pass-with-no-tests` | Pass khi không có test | false | Boolean |
| `--watch` | Chế độ watch | false | Boolean |
### Tùy chọn Merge
| Option | Mô tả | Default | Mục đích |
| ----------------------- | -------------------------- | ------------------------------- | ----------- |
| `--merge` | Gộp các báo cáo coverage | false | Merge mode |
| `--merge-output <path>` | Đường dẫn xuất file đã gộp | ./coverage/merged-coverage.json | Output path |
## Hướng dẫn sử dụng theo tình huống
### Development hàng ngày
```bash
# Chạy coverage với HTML report
npm run coverage
# Chạy coverage với watch mode
npm run coverage:watch
# Kiểm tra ngưỡng coverage
npm run coverage:check
```
### Before push
```bash
# Kiểm tra toàn bộ coverage với thresholds
npm run coverage:check
# Tạo comprehensive reports
npm run coverage:report
```
### CI/CD Pipeline
```bash
# CI mode với JSON và LCOV output
npm run coverage:ci
# Kiểm tra với custom thresholds
npx midi-cov --ci --threshold-global 90
# Merge coverage từ nhiều jobs (cùng thư mục)
npx midi-cov merge "coverage/*.json" --merge-output ./coverage/final-coverage.json
```
### Monorepo coverage
```bash
# Merge coverage từ các packages
npx midi-cov merge \
packages/*/coverage/coverage.json \
--merge-output ./coverage/monorepo-coverage.json
# Kiểm tra merged coverage
npx midi-cov --ci \
--report-json ./coverage/monorepo-coverage.json \
--threshold-global 80
```
## Coverage Configuration
### Jest Configuration
```javascript
// jest.config.js
module.exports = {
testEnvironment: 'node',
coverageProvider: 'babel',
transform: {
'^.+\.(ts|tsx)$': ['ts-jest', { isolatedModules: true }],
'^.+\.(js|jsx)$': 'babel-jest',
},
moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json'],
collectCoverage: true,
collectCoverageFrom: [
'src/**/*.service.{ts,js}',
'src/**/*.controller.{ts,js}',
'!src/**/*.spec.{ts,js}',
'!src/**/*.test.{ts,js}',
'!**/*.d.ts',
],
coverageDirectory: './coverage',
coveragePathIgnorePatterns: ['/node_modules/', '/dist/', '/coverage/', '/.next/', '/build/'],
coverageReporters: ['json', 'json-summary', 'text', 'html', 'lcov'],
coverageThreshold: {
global: { statements: 80, branches: 75, functions: 80, lines: 80 },
},
};
```
## Report Formats
### HTML Report
Báo cáo tương tác với:
- File-by-file coverage breakdown
- Source code highlighting
- Coverage heatmap
- Detailed metrics
```bash
npx midi-cov --report-html ./coverage/index.html
```
### LCOV Report
Format chuẩn cho:
- Codecov integration
- Coveralls integration
- SonarQube analysis
- IDE extensions
```bash
npx midi-cov --report-lcov ./coverage/lcov.info
```
### Cobertura XML
Format XML cho:
- Jenkins coverage plugin
- Azure DevOps pipelines
- GitLab CI/CD
- Bitbucket pipelines
```bash
npx midi-cov --report-cobertura ./coverage/cobertura.xml
```
### JSON Report
Machine-readable format cho:
- Custom processing
- API integration
- Coverage trending
- Data analysis
```bash
npx midi-cov --report-json ./coverage/coverage.json
```
## Threshold Enforcement
### Thiết lập ngưỡng
```bash
# Ngưỡng riêng cho từng metric
npx midi-cov --ci \
--threshold-statements 85 \
--threshold-branches 80 \
--threshold-functions 85 \
--threshold-lines 85
# Ngưỡng chung (trung bình các metrics)
npx midi-cov --ci --threshold-global 80
```
### Khi ngưỡng không đạt
Tool sẽ:
1. Exit với code 1 (failure)
2. Hiển thị chi tiết metrics không đạt
3. So sánh actual vs required percentages
4. Suggest các files cần improve
## Merging Coverage
### Use cases
- Multiple test suites (unit, integration, e2e)
- Parallel test execution
- Monorepo với nhiều packages
- Cross-platform testing
### Ví dụ merge
```bash
# Merge specific files
midi-cov merge \
coverage-unit.json \
coverage-integration.json \
coverage-e2e.json \
--merge-output merged-coverage.json
# Merge với glob pattern (đa thư mục)
midi-cov merge "**/coverage/coverage.json" \
--merge-output ./coverage/final.json
# Merge từ subdirectories
midi-cov merge \
"packages/*/coverage/coverage.json" \
--merge-output ./coverage/monorepo.json
```
## Ví dụ Output
### Check mode - Success
```bash
$ npm run coverage:check
[midi-cov] Analyzing coverage...
[midi-cov] ✅ Coverage Analysis Complete
Coverage Summary:
Statements: 182/200 (91%)
Branches: 48/60 (80%)
Functions: 35/40 (87.5%)
Lines: 175/195 (89.7%)
Threshold Status:
✅ Statements: 91% (threshold: 80%)
✅ Branches: 80% (threshold: 75%)
✅ Functions: 87.5% (threshold: 80%)
✅ Lines: 89.7% (threshold: 80%)
[midi-cov] Check mode - ✅ Passed
```
### Check mode - Failed
```bash
$ npm run coverage:check
[midi-cov] Analyzing coverage...
[midi-cov] ❌ Coverage thresholds not met
Coverage Summary:
Statements: 140/200 (70%)
Branches: 35/60 (58.3%)
Functions: 28/40 (70%)
Lines: 135/195 (69.2%)
Threshold Status:
❌ Statements: 70% (threshold: 80%)
❌ Branches: 58.3% (threshold: 75%)
❌ Functions: 70% (threshold: 80%)
❌ Lines: 69.2% (threshold: 80%)
[midi-cov] Check mode - ❌ Failed
```
### Merge output
```bash
$ npm run coverage:merge
[midi-cov] Merging coverage reports...
[midi-cov] Found 3 coverage files to merge
[midi-cov] ✅ Merged coverage report written to ./coverage/merged-coverage.json
Merged Coverage Summary:
Statements: 520/600 (86.67%)
Branches: 145/180 (80.56%)
Functions: 98/120 (81.67%)
Lines: 505/590 (85.59%)
```
## Quy trình đóng gói
### B1: Vào thư mục code-coverage, cài đặt dependencies và kiểm tra authentication với npm registry
```bash
cd packages/ci/code-coverage && npm install
npm whoami
# Nếu chưa đăng nhập, chạy lệnh:
npm login
```
### B2: Cần thay đổi các thông tin cần thiết trong file package.json nếu cần
```json
{
"name": "@hemidi/code-coverage", // <- Thay đổi tên package nếu cần
"version": "1.0.0", // <- Thay đổi version
"description": "Code coverage tool..." // <- Thay đổi mô tả
}
```
### B3: Quản lý version của package
```bash
# example
npm version patch # 1.0.1
npm version minor # 1.1.0
npm version major # 2.0.0
```
### B4: Build package
```bash
npm run build
```
### B5: Đóng gói và publish
```bash
# Đóng gói package public
npm publish --access public
# Đóng gói package private
npm publish --access restricted
```