网淘吧来吧,欢迎您!

返回首页 微信
微信
手机版
手机版

Test Runner技能使用说明

2026-03-26 新闻来源:网淘吧 围观:98
电脑广告
手机广告

测试运行器

跨语言和框架编写与运行测试。

框架选择

语言 单元测试 集成测试 端到端测试
TypeScript/JS Vitest (首选), Jest Supertest Playwright
Python pytest pytest + httpx Playwright
Swift XCTest XCTest XCUITest

按框架快速入门

Vitest (TypeScript / JavaScript)

npm install -D vitest @testing-library/react @testing-library/jest-dom
// vitest.config.ts
import { defineConfig } from 'vitest/config'
export default defineConfig({
  test: {
    globals: true,
    environment: 'jsdom',
    setupFiles: './tests/setup.ts',
  },
})
npx vitest              # 监听模式
npx vitest run          # 单次运行
npx vitest --coverage   # 带覆盖率报告

Jest

npm install -D jest @types/jest ts-jest
npx jest                # 运行所有测试
npx jest --watch        # 监听模式
npx jest --coverage     # 带覆盖率报告
npx jest path/to/test   # 运行单个文件

pytest (Python)

uv pip install pytest pytest-cov pytest-asyncio httpx
pytest                          # 运行所有测试
pytest -v                       # 详细输出
pytest -x                       # 首次失败即停止
pytest --cov=app                # 带覆盖率报告
pytest tests/test_api.py -k "test_login"  # 运行特定测试
pytest --tb=short               # 简短回溯信息

XCTest (Swift)

swift test                      # 运行所有测试
swift test --filter MyTests     # 运行特定测试套件
swift test --parallel           # 并行执行

Playwright (端到端测试)

npm install -D @playwright/test
npx playwright install
npx playwright test                    # 运行所有测试
npx playwright test --headed           # 浏览器可见模式
npx playwright test --debug            # 调试模式
npx playwright test --project=chromium # 指定浏览器
npx playwright show-report             # 查看HTML报告

TDD 工作流程

  1. — 编写一个描述期望行为的失败测试。
  2. 绿— 编写最少的代码使测试通过。
  3. 重构— 清理代码,同时保持测试通过。
┌─────────┐     ┌─────────┐     ┌──────────┐
│   编写   │────▶│   编写  │────▶│   重构   │──┐
│   测试   │     │   代码  │     │   代码   │  │
│  (红)  │     │ (绿)  │     │          │  │
└─────────┘     └─────────┘     └──────────┘  │
     ▲                                          │
     └──────────────────────────────────────────┘

测试模式

准备-执行-断言

test('计算含税总额', () => {
  // 准备
  const cart = new Cart([{ price: 100, qty: 2 }]);

  // 执行
  const total = cart.totalWithTax(0.08);

  // 断言
  expect(total).toBe(216);
});

测试异步代码

test('获取用户数据', async () => {
  const user = await getUser('123');
  expect(user.name).toBe('Colt');
});

模拟

import { vi } from 'vitest';

const mockFetch = vi.fn().mockResolvedValue({
  json: () => Promise.resolve({ id: 1, name: 'Test' }),
});
vi.stubGlobal('fetch', mockFetch);

测试API端点 (Python)

import pytest
from httpx import AsyncClient
from app.main import app

@pytest.mark.asyncio
async def test_get_users():
    async with AsyncClient(app=app, base_url="http://test") as client:
        response = await client.get("/users")
    assert response.status_code == 200
    assert isinstance(response.json(), list)

测试React组件

import { render, screen, fireEvent } from '@testing-library/react';
import { Button } from './Button';

test('calls onClick when clicked', () => {
  const handleClick = vi.fn();
  render(<Button onClick={handleClick}>Click me</Button>);
  fireEvent.click(screen.getByText('Click me'));
  expect(handleClick).toHaveBeenCalledOnce();
});

覆盖率命令

# JavaScript/TypeScript
npx vitest --coverage          # Vitest (使用 v8 或 istanbul)
npx jest --coverage            # Jest

# Python
pytest --cov=app --cov-report=html    # HTML报告
pytest --cov=app --cov-report=term    # 终端输出
pytest --cov=app --cov-fail-under=80  # 覆盖率低于80%时失败

# 查看HTML覆盖率报告
open coverage/index.html       # macOS
open htmlcov/index.html        # Python

测试什么

始终测试:

  • 公共API / 导出的函数
  • 边界情况:空输入、空值、边界值
  • 错误处理:无效输入、网络故障
  • 业务逻辑:计算、状态转换

无需测试:

  • 私有实现细节
  • 框架内部机制(React渲染、Express路由)
  • 简单的getter/setter方法
  • 第三方库的行为

天猫隐藏优惠券

网淘吧

免责申明
部分文章来自各大搜索引擎,如有侵权,请与我联系删除。
打赏
文章底部电脑广告
手机广告位-内容正文底部

相关文章

您是本站第278629名访客 今日有72篇新文章/评论