怎样用脚本自动运行单元测试?

wen 实用脚本 2

本文目录导读:

怎样用脚本自动运行单元测试?

  1. 使用 npm scripts(最常用)
  2. 使用 Makefile
  3. 使用 Husky + lint-staged(Git hooks)
  4. 脚本自动运行(Python 示例)
  5. Shell 脚本自动化
  6. CI/CD 配置示例
  7. 自动运行脚本(Node.js)
  8. 使用建议

使用 npm scripts(最常用)

package.json 中配置:

{
  "scripts": {
    "test": "jest",
    "test:watch": "jest --watch",
    "test:coverage": "jest --coverage",
    "test:ci": "jest --ci --coverage --maxWorkers=2"
  }
}

运行:

npm test           # 运行一次
npm run test:watch # 持续监听文件变化
npm run test:ci    # CI环境运行

使用 Makefile

.PHONY: test test-watch test-coverage
test:
    npm test
test-watch:
    npx jest --watch
test-coverage:
    npx jest --coverage
test-all:
    npm test
    npm run lint
# 在提交前自动运行
pre-commit: test
    @echo "所有测试通过 ✓"

使用:

make test
make test-watch

使用 Husky + lint-staged(Git hooks)

安装配置:

npm install husky lint-staged --save-dev

package.json 配置:

{
  "husky": {
    "hooks": {
      "pre-commit": "lint-staged",
      "pre-push": "npm test"
    }
  },
  "lint-staged": {
    "*.{js,jsx,ts,tsx}": [
      "eslint --fix",
      "jest --findRelatedTests --bail"
    ]
  }
}

脚本自动运行(Python 示例)

run_tests.py:

#!/usr/bin/env python3
import subprocess
import sys
import time
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
class TestRunner(FileSystemEventHandler):
    def on_modified(self, event):
        if event.src_path.endswith('.py') or event.src_path.endswith('.test.js'):
            print(f"\n检测到文件变化: {event.src_path}")
            self.run_tests()
    def run_tests(self):
        print("运行测试...")
        result = subprocess.run(['npm', 'test'], capture_output=True, text=True)
        print(result.stdout)
        if result.returncode != 0:
            print("❌ 测试失败!")
        else:
            print("✅ 测试通过!")
if __name__ == "__main__":
    event_handler = TestRunner()
    observer = Observer()
    observer.schedule(event_handler, path='./src', recursive=True)
    observer.start()
    print("开始监控文件变化...")
    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        observer.stop()
    observer.join()

Shell 脚本自动化

auto_test.sh:

#!/bin/bash
# 配置
WATCH_DIR="./src"
TEST_COMMAND="npm test"
# 颜色输出
GREEN='\033[0;32m'
RED='\033[0;31m'
NC='\033[0m'
# 运行测试
run_tests() {
    echo -e "${GREEN}运行测试...${NC}"
    if $TEST_COMMAND; then
        echo -e "${GREEN}✅ 测试通过${NC}"
    else
        echo -e "${RED}❌ 测试失败${NC}"
    fi
}
# 监听文件变化(需要安装 inotify-tools)
if command -v inotifywait &> /dev/null; then
    echo "开始监听 $WATCH_DIR ..."
    while inotifywait -r -e modify $WATCH_DIR; do
        run_tests
    done
else
    echo "使用轮询模式..."
    while true; do
        run_tests
        sleep 60  # 每60秒运行一次
    done
fi

CI/CD 配置示例

GitHub Actions

# .github/workflows/test.yml
name: Run Tests
on: [push, pull_request]
jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
      - name: Install dependencies
        run: npm ci
      - name: Run tests
        run: npm test
        env:
          CI: true

Jenkins Pipeline

// Jenkinsfile
pipeline {
    agent any
    stages {
        stage('Install') {
            steps {
                sh 'npm install'
            }
        }
        stage('Test') {
            steps {
                sh 'npm test'
            }
        }
    }
    post {
        always {
            junit 'reports/**/*.xml'
        }
    }
}

自动运行脚本(Node.js)

auto-runner.js:

const chokidar = require('chokidar');
const { exec } = require('child_process');
const watcher = chokidar.watch('./src/**/*.{js,jsx,ts,tsx}', {
  ignored: /node_modules/,
  persistent: true
});
let testTimeout;
watcher.on('change', (path) => {
  console.log(`文件变化: ${path}`);
  // 防抖,避免频繁触发
  clearTimeout(testTimeout);
  testTimeout = setTimeout(() => {
    console.log('运行测试...');
    exec('npm test', (err, stdout, stderr) => {
      if (err) {
        console.error('测试失败:', stderr);
      } else {
        console.log('测试通过:', stdout);
      }
    });
  }, 1000);
});
console.log('开始监控...');

启动方式:

node auto-runner.js

使用建议

  1. 开发环境:使用 jest --watch 实时反馈
  2. 提交前:使用 Husky + lint-staged 自动运行
  3. CI环境:配置完整的测试流水线
  4. 定时任务:配置 cron job 定期运行

这样可以根据不同场景选择合适的自动化方案!

抱歉,评论功能暂时关闭!