test-automator

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Test Automator

测试自动化专家

Expert in creating and maintaining automated tests for various frameworks and languages.
擅长为各类框架和语言创建并维护自动化测试。

When This Skill Activates

该技能触发场景

Activates when you:
  • Ask to write tests
  • Mention test automation
  • Request test coverage improvement
  • Need to set up testing framework
当你进行以下操作时触发:
  • 要求编写测试
  • 提及测试自动化
  • 请求提升测试覆盖率
  • 需要搭建测试框架

Testing Pyramid

测试金字塔

        /\
       /E2E\      - Few, expensive, slow
      /------\
     /  Integration \ - Moderate number
    /--------------\
   /     Unit Tests  \ - Many, cheap, fast
  /------------------\
        /\
       /E2E\      - 数量少、成本高、速度慢
      /------\
     /  Integration \ - 数量适中
    /--------------\
   /     Unit Tests  \ - 数量多、成本低、速度快
  /------------------\

Unit Testing

单元测试

Principles

原则

  1. Test behavior, not implementation
  2. One assertion per test (generally)
  3. Arrange-Act-Assert pattern
  4. Descriptive test names
  1. 测试行为,而非实现细节
  2. 每个测试通常仅包含一个断言
  3. Arrange-Act-Assert(准备-执行-断言)模式
  4. 描述性的测试名称

Example (Jest)

示例(Jest)

typescript
describe('UserService', () => {
  describe('createUser', () => {
    it('should create a user with valid data', async () => {
      // Arrange
      const userData = {
        name: 'John Doe',
        email: 'john@example.com'
      };

      // Act
      const user = await userService.create(userData);

      // Assert
      expect(user.id).toBeDefined();
      expect(user.email).toBe(userData.email);
    });

    it('should throw error for invalid email', async () => {
      // Arrange
      const userData = { email: 'invalid' };

      // Act & Assert
      await expect(userService.create(userData))
        .rejects.toThrow('Invalid email');
    });
  });
});
typescript
describe('UserService', () => {
  describe('createUser', () => {
    it('should create a user with valid data', async () => {
      // Arrange
      const userData = {
        name: 'John Doe',
        email: 'john@example.com'
      };

      // Act
      const user = await userService.create(userData);

      // Assert
      expect(user.id).toBeDefined();
      expect(user.email).toBe(userData.email);
    });

    it('should throw error for invalid email', async () => {
      // Arrange
      const userData = { email: 'invalid' };

      // Act & Assert
      await expect(userService.create(userData))
        .rejects.toThrow('Invalid email');
    });
  });
});

Integration Testing

集成测试

Principles

原则

  1. Test component interactions
  2. Use test doubles for external services
  3. Clean up test data
  4. Run in isolation
  1. 测试组件间的交互
  2. 为外部服务使用测试替身(Test Doubles)
  3. 清理测试数据
  4. 独立运行测试

Example (Supertest)

示例(Supertest)

typescript
describe('POST /api/users', () => {
  it('should create a user', async () => {
    const response = await request(app)
      .post('/api/users')
      .send({
        name: 'John Doe',
        email: 'john@example.com'
      })
      .expect(201)
      .expect((res) => {
        expect(res.body.id).toBeDefined();
        expect(res.body.email).toBe('john@example.com');
      });
  });
});
typescript
describe('POST /api/users', () => {
  it('should create a user', async () => {
    const response = await request(app)
      .post('/api/users')
      .send({
        name: 'John Doe',
        email: 'john@example.com'
      })
      .expect(201)
      .expect((res) => {
        expect(res.body.id).toBeDefined();
        expect(res.body.email).toBe('john@example.com');
      });
  });
});

E2E Testing

E2E测试

Principles

原则

  1. Test critical user flows
  2. Use realistic test data
  3. Handle async operations properly
  4. Clean up after tests
  1. 测试关键用户流程
  2. 使用真实的测试数据
  3. 正确处理异步操作
  4. 测试后清理环境

Example (Playwright)

示例(Playwright)

typescript
test('user can login', async ({ page }) => {
  await page.goto('/login');
  await page.fill('[name="email"]', 'user@example.com');
  await page.fill('[name="password"]', 'password123');
  await page.click('button[type="submit"]');

  await expect(page).toHaveURL('/dashboard');
  await expect(page.locator('h1')).toContainText('Welcome');
});
typescript
test('user can login', async ({ page }) => {
  await page.goto('/login');
  await page.fill('[name="email"]', 'user@example.com');
  await page.fill('[name="password"]', 'password123');
  await page.click('button[type="submit"]');

  await expect(page).toHaveURL('/dashboard');
  await expect(page.locator('h1')).toContainText('Welcome');
});

Test Coverage

测试覆盖率

Coverage Goals

覆盖率目标

TypeTarget
Lines> 80%
Branches> 75%
Functions> 80%
Statements> 80%
类型目标
代码行> 80%
分支> 75%
函数> 80%
语句> 80%

Coverage Reports

覆盖率报告

bash
undefined
bash
undefined

Jest

Jest

npm test -- --coverage
npm test -- --coverage

Python (pytest-cov)

Python (pytest-cov)

pytest --cov=src --cov-report=html
pytest --cov=src --cov-report=html

Go

Go

go test -coverprofile=coverage.out go tool cover -html=coverage.out
undefined
go test -coverprofile=coverage.out go tool cover -html=coverage.out
undefined

Testing Best Practices

测试最佳实践

DO's

建议事项

  • Write tests before fixing bugs (TDD)
  • Test edge cases
  • Keep tests independent
  • Use descriptive test names
  • Mock external dependencies
  • Clean up test data
  • 修复Bug前先编写测试(TDD)
  • 测试边缘情况
  • 保持测试独立性
  • 使用描述性的测试名称
  • 模拟外部依赖
  • 清理测试数据

DON'Ts

禁忌事项

  • Don't test implementation details
  • Don't write brittle tests
  • Don't skip tests without a reason
  • Don't commit commented-out tests
  • Don't test third-party libraries
  • 不要测试实现细节
  • 不要编写脆弱的测试
  • 无正当理由不要跳过测试
  • 不要提交被注释掉的测试
  • 不要测试第三方库

Test Naming Conventions

测试命名规范

typescript
// Good: Describes what is being tested
it('should reject invalid email addresses')

// Good: Describes the scenario and outcome
it('returns 401 when user provides invalid credentials')

// Bad: Vague
it('works correctly')
typescript
// Good: Describes what is being tested
it('should reject invalid email addresses')

// Good: Describes the scenario and outcome
it('returns 401 when user provides invalid credentials')

// Bad: Vague
it('works correctly')

Common Testing Frameworks

常用测试框架

LanguageFrameworkCommand
TypeScript/JSJest, Vitest
npm test
Pythonpytest
pytest
Gotesting
go test
JavaJUnit
mvn test
Rustbuilt-in
cargo test
语言框架命令
TypeScript/JSJest, Vitest
npm test
Pythonpytest
pytest
Gotesting
go test
JavaJUnit
mvn test
Rust内置测试框架
cargo test

Scripts

脚本工具

Generate test boilerplate:
bash
python scripts/generate_test.py <filename>
Check test coverage:
bash
python scripts/coverage_report.py
生成测试模板:
bash
python scripts/generate_test.py <filename>
检查测试覆盖率:
bash
python scripts/coverage_report.py

References

参考资料

  • references/best-practices.md
    - Testing best practices
  • references/examples/
    - Framework-specific examples
  • references/mocking.md
    - Mocking guidelines
  • references/best-practices.md
    - 测试最佳实践
  • references/examples/
    - 框架专属示例
  • references/mocking.md
    - 模拟指南