test-generator

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese
<identity> Test Generator Skill - Generates test code from specifications, components, and API endpoints following project testing patterns and conventions. </identity> <capabilities> - Generating tests for new components - Creating tests for API endpoints - Generating E2E tests for user flows - Creating integration tests - Adding test coverage for existing code </capabilities> <instructions> <execution_process>
<identity> 测试生成Skill - 根据项目测试模式和规范,从需求规格、组件和API端点生成测试代码。 </identity> <capabilities> - 为新组件生成测试 - 为API端点创建测试 - 为用户流程生成E2E测试 - 创建集成测试 - 为现有代码补充测试覆盖率 </capabilities> <instructions> <execution_process>

Step 1: Identify Test Type

步骤1:确定测试类型

Determine what type of test is needed:
  • Unit Test: Component/function testing
  • Integration Test: Service/API integration
  • E2E Test: Full user flow testing
  • API Test: Endpoint testing
确定所需的测试类型:
  • Unit Test(单元测试):组件/函数测试
  • Integration Test(集成测试):服务/API集成测试
  • E2E Test(端到端测试):完整用户流程测试
  • API Test(API测试):端点测试

Step 2: Analyze Target Code

步骤2:分析目标代码

Examine code to test:
  • Read component/function code
  • Identify test cases
  • Understand dependencies
  • Note edge cases
检查待测试的代码:
  • 阅读组件/函数代码
  • 确定测试用例
  • 理解依赖关系
  • 记录边缘情况

Step 3: Analyze Test Patterns

步骤3:分析测试模式

Review existing tests:
  • Read similar test files
  • Identify testing patterns
  • Note testing framework usage
  • Understand mocking strategies
审查现有测试:
  • 阅读类似的测试文件
  • 识别测试模式
  • 记录测试框架的使用情况
  • 理解模拟策略

Step 4: Generate Test Code

步骤4:生成测试代码

Create test following patterns:
  • Use appropriate testing framework
  • Follow project conventions
  • Include comprehensive coverage
  • Add edge cases and error scenarios
遵循模式创建测试:
  • 使用合适的测试框架
  • 遵循项目规范
  • 包含全面的测试覆盖
  • 加入边缘情况和错误场景

Step 5: Coverage Analysis

步骤5:覆盖率分析

After generating tests, analyze coverage:
  1. Check that generated tests cover all requirements:
    • Verify all functions/methods are tested
    • Check all branches are covered (if/else, switch, etc.)
    • Ensure all edge cases are tested
    • Validate error scenarios are covered
  2. Validate tests are runnable:
    • Check test syntax is valid
    • Verify imports are correct
    • Ensure test framework is properly configured
    • Validate test setup/teardown is correct
  3. Report coverage percentage:
    • Calculate line coverage (if possible)
    • Calculate branch coverage (if possible)
    • Report uncovered code paths
    • Suggest additional tests for uncovered areas
  4. Coverage Validation Checklist:
    • All public functions/methods have tests
    • All error paths are tested
    • All edge cases are covered
    • Tests are syntactically valid
    • Tests can be executed successfully
    • Coverage meets project thresholds (if defined) </execution_process> </instructions>
<examples> <code_example> **Unit Test (React Component)**
typescript
import { render, screen, waitFor } from '@testing-library/react'
import { describe, it, expect, vi } from 'vitest'
import { UserProfile } from './user-profile'

describe('UserProfile', () => {
  it('renders user information', async () => {
    const mockUser = { id: '1', name: 'John', email: 'john@example.com' }

    render(<UserProfile user={mockUser} />)

    await waitFor(() => {
      expect(screen.getByText('John')).toBeInTheDocument()
      expect(screen.getByText('john@example.com')).toBeInTheDocument()
    })
  })

  it('handles loading state', () => {
    render(<UserProfile user={null} loading />)
    expect(screen.getByTestId('loading')).toBeInTheDocument()
  })

  it('handles error state', () => {
    render(<UserProfile user={null} error="Failed to load" />)
    expect(screen.getByText('Failed to load')).toBeInTheDocument()
  })
})
</code_example>
<code_example> Integration Test (API)
typescript
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
import { createTestClient } from './test-client';

describe('Users API', () => {
  let client: TestClient;

  beforeAll(() => {
    client = createTestClient();
  });

  afterAll(async () => {
    await client.cleanup();
  });

  it('creates a user', async () => {
    const response = await client.post('/api/users', {
      email: 'test@example.com',
      name: 'Test User',
    });

    expect(response.status).toBe(201);
    expect(response.data).toHaveProperty('id');
    expect(response.data.email).toBe('test@example.com');
  });

  it('validates required fields', async () => {
    const response = await client.post('/api/users', {});

    expect(response.status).toBe(400);
    expect(response.data).toHaveProperty('errors');
  });
});
</code_example>
<code_example> E2E Test (Cypress)
typescript
describe('User Authentication Flow', () => {
  beforeEach(() => {
    cy.visit('/login');
  });

  it('allows user to login', () => {
    cy.get('[data-testid="email-input"]').type('user@example.com');
    cy.get('[data-testid="password-input"]').type('password123');
    cy.get('[data-testid="login-button"]').click();

    cy.url().should('include', '/dashboard');
    cy.get('[data-testid="user-menu"]').should('be.visible');
  });

  it('shows error for invalid credentials', () => {
    cy.get('[data-testid="email-input"]').type('invalid@example.com');
    cy.get('[data-testid="password-input"]').type('wrong');
    cy.get('[data-testid="login-button"]').click();

    cy.get('[data-testid="error-message"]')
      .should('be.visible')
      .and('contain', 'Invalid credentials');
  });
});
</code_example> </examples>
<instructions> <integration> **Integration with Developer Agent**: - Generates tests during development - Ensures test coverage - Validates implementation
Integration with QA Agent:
  • Creates comprehensive test suites
  • Generates test plans
  • Validates test quality </integration>
<best_practices>
  1. Follow Patterns: Match existing test structure
  2. Comprehensive Coverage: Test happy paths and edge cases
  3. Clear Test Names: Descriptive test descriptions
  4. Isolate Tests: Each test should be independent
  5. Mock Dependencies: Use appropriate mocking strategies </best_practices> </instructions>
<examples> <usage_example> **Example Commands**:
undefined
生成测试后,分析覆盖率:
  1. 验证生成的测试覆盖所有需求
    • 确认所有函数/方法都已测试
    • 检查所有分支都已覆盖(if/else、switch等)
    • 确保所有边缘情况都已测试
    • 验证错误场景都已覆盖
  2. 验证测试可运行
    • 检查测试语法是否有效
    • 验证导入是否正确
    • 确保测试框架配置正确
    • 验证测试的前置/后置处理是否正确
  3. 报告覆盖率百分比
    • 计算行覆盖率(如果可能)
    • 计算分支覆盖率(如果可能)
    • 报告未覆盖的代码路径
    • 为未覆盖区域建议额外测试
  4. 覆盖率验证清单
    • 所有公共函数/方法都有测试
    • 所有错误路径都已测试
    • 所有边缘情况都已覆盖
    • 测试语法有效
    • 测试可成功执行
    • 覆盖率达到项目阈值(如果已定义) </execution_process> </instructions>
<examples> <code_example> **Unit Test(单元测试,React组件)**
typescript
import { render, screen, waitFor } from '@testing-library/react'
import { describe, it, expect, vi } from 'vitest'
import { UserProfile } from './user-profile'

describe('UserProfile', () => {
  it('renders user information', async () => {
    const mockUser = { id: '1', name: 'John', email: 'john@example.com' }

    render(<UserProfile user={mockUser} />)

    await waitFor(() => {
      expect(screen.getByText('John')).toBeInTheDocument()
      expect(screen.getByText('john@example.com')).toBeInTheDocument()
    })
  })

  it('handles loading state', () => {
    render(<UserProfile user={null} loading />)
    expect(screen.getByTestId('loading')).toBeInTheDocument()
  })

  it('handles error state', () => {
    render(<UserProfile user={null} error="Failed to load" />)
    expect(screen.getByText('Failed to load')).toBeInTheDocument()
  })
})
</code_example>
<code_example> Integration Test(集成测试,API)
typescript
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
import { createTestClient } from './test-client';

describe('Users API', () => {
  let client: TestClient;

  beforeAll(() => {
    client = createTestClient();
  });

  afterAll(async () => {
    await client.cleanup();
  });

  it('creates a user', async () => {
    const response = await client.post('/api/users', {
      email: 'test@example.com',
      name: 'Test User',
    });

    expect(response.status).toBe(201);
    expect(response.data).toHaveProperty('id');
    expect(response.data.email).toBe('test@example.com');
  });

  it('validates required fields', async () => {
    const response = await client.post('/api/users', {});

    expect(response.status).toBe(400);
    expect(response.data).toHaveProperty('errors');
  });
});
</code_example>
<code_example> E2E Test(端到端测试,Cypress)
typescript
describe('User Authentication Flow', () => {
  beforeEach(() => {
    cy.visit('/login');
  });

  it('allows user to login', () => {
    cy.get('[data-testid="email-input"]').type('user@example.com');
    cy.get('[data-testid="password-input"]').type('password123');
    cy.get('[data-testid="login-button"]').click();

    cy.url().should('include', '/dashboard');
    cy.get('[data-testid="user-menu"]').should('be.visible');
  });

  it('shows error for invalid credentials', () => {
    cy.get('[data-testid="email-input"]').type('invalid@example.com');
    cy.get('[data-testid="password-input"]').type('wrong');
    cy.get('[data-testid="login-button"]').click();

    cy.get('[data-testid="error-message"]')
      .should('be.visible')
      .and('contain', 'Invalid credentials');
  });
});
</code_example> </examples>
<instructions> <integration> **与Developer Agent集成**: - 在开发过程中生成测试 - 确保测试覆盖率 - 验证实现
与QA Agent集成:
  • 创建全面的测试套件
  • 生成测试计划
  • 验证测试质量 </integration>
<best_practices>
  1. 遵循模式:匹配现有测试结构
  2. 全面覆盖:测试正常路径和边缘情况
  3. 清晰的测试名称:描述性的测试说明
  4. 隔离测试:每个测试应独立
  5. 模拟依赖:使用合适的模拟策略 </best_practices> </instructions>
<examples> <usage_example> **示例命令**:
undefined

Generate unit tests

生成单元测试

Generate unit tests for components/user-profile
Generate unit tests for components/user-profile

Generate API tests

生成API测试

Generate API tests for app/api/users
Generate API tests for app/api/users

Generate E2E tests

生成E2E测试

Generate E2E tests for user authentication flow
Generate E2E tests for user authentication flow

Generate integration tests

生成集成测试

Generate integration tests for user service

</usage_example>
</examples>
Generate integration tests for user service

</usage_example>
</examples>