typescript-e2e-testing

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

E2E Testing Skill

E2E测试技能

E2E testing validates complete workflows from user perspective, using real infrastructure via Docker.

E2E测试从用户视角验证完整工作流,使用Docker提供的真实基础设施。

Workflows

工作流

For comprehensive step-by-step guidance, use the appropriate workflow:
WorkflowWhen to Use
Setup E2E TestSetting up E2E infrastructure for a new or existing project
Writing E2E TestCreating new E2E test cases with proper GWT pattern
Review E2E TestReviewing existing tests for quality and correctness
Running E2E TestExecuting tests with proper verification
Debugging E2E TestSystematically fixing failing tests
Optimize E2E TestImproving test suite performance
如需全面的分步指导,请使用对应的工作流:
工作流使用场景
搭建E2E测试为新项目或现有项目搭建E2E测试基础设施
编写E2E测试使用标准GWT模式创建新的E2E测试用例
评审E2E测试评审现有测试的质量和正确性
运行E2E测试正确执行测试并验证结果
调试E2E测试系统化修复失败的测试
优化E2E测试提升测试套件的性能

Workflow Selection Guide

工作流选择指南

IMPORTANT: Before starting any E2E testing task, identify the user's intent and load the appropriate workflow.
重要提示:在开始任何E2E测试任务前,请先明确用户的需求,再加载对应的工作流。

Detect User Intent → Select Workflow

识别用户需求 → 选择工作流

User Says / WantsWorkflow to LoadFile
"Set up E2E tests", "configure docker-compose", "add E2E to project", "create test helpers"Setup
workflows/setup/workflow.md
"Write E2E tests", "add integration tests", "test this endpoint", "create e2e-spec"Writing
workflows/writing/workflow.md
"Review E2E tests", "check test quality", "audit tests", "is this test correct?"Reviewing
workflows/review/workflow.md
"Run E2E tests", "execute tests", "start docker and test", "check if tests pass"Running
workflows/running/workflow.md
"Fix E2E tests", "debug tests", "tests are failing", "flaky test", "connection error"Debugging
workflows/debugging/workflow.md
"Speed up E2E tests", "optimize tests", "tests are slow", "reduce test time"Optimizing
workflows/optimize/workflow.md
用户需求加载的工作流文件
"搭建E2E测试"、"配置docker-compose"、"为项目添加E2E测试"、"创建测试辅助工具"搭建
workflows/setup/workflow.md
"编写E2E测试"、"添加集成测试"、"测试这个接口"、"创建e2e-spec文件"编写
workflows/writing/workflow.md
"评审E2E测试"、"检查测试质量"、"审计测试"、"这个测试是否正确?"评审
workflows/review/workflow.md
"运行E2E测试"、"执行测试"、"启动Docker并测试"、"检查测试是否通过"运行
workflows/running/workflow.md
"修复E2E测试"、"调试测试"、"测试失败了"、"不稳定测试"、"连接错误"调试
workflows/debugging/workflow.md
"加速E2E测试"、"优化测试"、"测试太慢了"、"减少测试时间"优化
workflows/optimize/workflow.md

Workflow Execution Protocol

工作流执行规范

  1. ALWAYS load the workflow file first - Read the full workflow before taking action
  2. Follow each step in order - Complete checkpoints before proceeding
  3. Load knowledge files as directed - Each workflow specifies which
    references/
    files to read
  4. Verify compliance after completion - Re-read relevant reference files to ensure quality
Important: Each workflow includes instructions to load relevant knowledge from the
references/
folder before and after completing tasks.

  1. 务必先加载工作流文件 - 在执行操作前通读完整工作流
  2. 按顺序执行每一步 - 完成检查点后再继续下一步
  3. 按指示加载知识库文件 - 每个工作流会指定需要读取的
    references/
    目录下的文件
  4. 完成后验证合规性 - 重新阅读相关参考文件以确保质量
重要提示:每个工作流都会要求在完成任务前后从
references/
文件夹加载相关知识。

Knowledge Base Structure

知识库结构

references/
├── common/              # Shared testing fundamentals
│   ├── knowledge.md     # Core E2E concepts and test pyramid
│   ├── rules.md         # Mandatory testing rules (GWT, timeouts, logging)
│   ├── best-practices.md # Test design and cleanup patterns
│   ├── test-case-creation-guide.md # GWT templates for all scenarios
│   ├── nestjs-setup.md  # NestJS app bootstrap and Jest config
│   ├── debugging.md     # VS Code config and log analysis
│   └── examples.md      # Comprehensive examples by category
├── kafka/               # Kafka-specific testing
│   ├── knowledge.md     # Why common approaches fail, architecture
│   ├── rules.md         # Kafka-specific testing rules
│   ├── test-helper.md   # KafkaTestHelper implementation
│   ├── docker-setup.md  # Redpanda/Kafka Docker configs
│   ├── performance.md   # Optimization techniques
│   ├── isolation.md     # Pre-subscription pattern details
│   └── examples.md      # Kafka test examples
├── postgres/            # PostgreSQL-specific testing
│   ├── knowledge.md     # PostgreSQL testing concepts
│   ├── rules.md         # Cleanup, transaction, assertion rules
│   ├── test-helper.md   # PostgresTestHelper implementation
│   └── examples.md      # CRUD, transaction, constraint examples
├── mongodb/             # MongoDB-specific testing
│   ├── knowledge.md     # MongoDB testing concepts
│   ├── rules.md         # Document cleanup and assertion rules
│   ├── test-helper.md   # MongoDbTestHelper implementation
│   ├── docker-setup.md  # Docker and Memory Server setup
│   └── examples.md      # Document and aggregation examples
├── redis/               # Redis-specific testing
│   ├── knowledge.md     # Redis testing concepts
│   ├── rules.md         # TTL and pub/sub rules
│   ├── test-helper.md   # RedisTestHelper implementation
│   ├── docker-setup.md  # Docker configuration
│   └── examples.md      # Cache, session, rate limit examples
└── api/                 # API testing (REST, GraphQL, gRPC)
    ├── knowledge.md     # API testing concepts
    ├── rules.md         # Request/response assertion rules
    ├── test-helper.md   # Auth and Supertest helpers
    ├── examples.md      # REST, GraphQL, validation examples
    └── mocking.md       # MSW and Nock external API mocking
references/
├── common/              # 通用测试基础
│   ├── knowledge.md     # 核心E2E概念和测试金字塔
│   ├── rules.md         # 强制性测试规则(GWT、超时、日志)
│   ├── best-practices.md # 测试设计和清理模式
│   ├── test-case-creation-guide.md # 适用于所有场景的GWT模板
│   ├── nestjs-setup.md  # NestJS应用启动和Jest配置
│   ├── debugging.md     # VS Code配置和日志分析
│   └── examples.md      # 按分类整理的综合示例
├── kafka/               # Kafka专属测试内容
│   ├── knowledge.md     # 常规方法失效的原因、架构说明
│   ├── rules.md         # Kafka专属测试规则
│   ├── test-helper.md   # KafkaTestHelper实现方案
│   ├── docker-setup.md  # Redpanda/Kafka Docker配置
│   ├── performance.md   # 优化技巧
│   ├── isolation.md     # 预订阅模式细节
│   └── examples.md      # Kafka测试示例
├── postgres/            # PostgreSQL专属测试内容
│   ├── knowledge.md     # PostgreSQL测试概念
│   ├── rules.md         # 清理、事务、断言规则
│   ├── test-helper.md   # PostgresTestHelper实现方案
│   └── examples.md      # CRUD、事务、约束示例
├── mongodb/             # MongoDB专属测试内容
│   ├── knowledge.md     # MongoDB测试概念
│   ├── rules.md         # 文档清理和断言规则
│   ├── test-helper.md   # MongoDbTestHelper实现方案
│   ├── docker-setup.md  # Docker和内存服务器配置
│   └── examples.md      # 文档和聚合查询示例
├── redis/               # Redis专属测试内容
│   ├── knowledge.md     # Redis测试概念
│   ├── rules.md         # TTL和发布/订阅规则
│   ├── test-helper.md   # RedisTestHelper实现方案
│   ├── docker-setup.md  # Docker配置
│   └── examples.md      # 缓存、会话、限流示例
└── api/                 # API测试(REST、GraphQL、gRPC)
    ├── knowledge.md     # API测试概念
    ├── rules.md         # 请求/响应断言规则
    ├── test-helper.md   # 认证和Supertest辅助工具
    ├── examples.md      # REST、GraphQL、验证示例
    └── mocking.md       # MSW和Nock外部API模拟

Quick Reference by Task

按任务分类的快速参考

Tip: For detailed step-by-step guidance, use the Workflows section above.
提示:如需详细的分步指导,请使用上方的工作流部分。

Setup New E2E Structure

搭建新的E2E测试结构

Workflow: Setup E2E Test
  1. Read
    references/common/knowledge.md
    - Understand E2E fundamentals
  2. Read
    references/common/nestjs-setup.md
    - Project setup
  3. Read technology-specific
    docker-setup.md
    files as needed
工作流搭建E2E测试
  1. 阅读
    references/common/knowledge.md
    - 理解E2E核心概念
  2. 阅读
    references/common/nestjs-setup.md
    - 项目搭建指南
  3. 根据需要阅读对应技术的
    docker-setup.md
    文件

Write Test Cases

编写测试用例

Workflow: Writing E2E Test
  1. MANDATORY: Read
    references/common/rules.md
    - GWT pattern, timeouts
  2. Read
    references/common/test-case-creation-guide.md
    - Templates
  3. Read technology-specific files:
    • Kafka:
      references/kafka/knowledge.md
      test-helper.md
      isolation.md
    • PostgreSQL:
      references/postgres/rules.md
      test-helper.md
    • MongoDB:
      references/mongodb/rules.md
      test-helper.md
    • Redis:
      references/redis/rules.md
      test-helper.md
    • API:
      references/api/rules.md
      test-helper.md
工作流编写E2E测试
  1. 必须:阅读
    references/common/rules.md
    - GWT模式、超时规则
  2. 阅读
    references/common/test-case-creation-guide.md
    - 测试用例模板
  3. 阅读对应技术的文件:
    • Kafka
      references/kafka/knowledge.md
      test-helper.md
      isolation.md
    • PostgreSQL
      references/postgres/rules.md
      test-helper.md
    • MongoDB
      references/mongodb/rules.md
      test-helper.md
    • Redis
      references/redis/rules.md
      test-helper.md
    • API
      references/api/rules.md
      test-helper.md

Review Test Quality

评审测试质量

Workflow: Review E2E Test
  1. Read
    references/common/rules.md
    - Check against mandatory patterns
  2. Read
    references/common/best-practices.md
    - Quality standards
  3. Read technology-specific
    rules.md
    files
工作流评审E2E测试
  1. 阅读
    references/common/rules.md
    - 检查是否符合强制性模式
  2. 阅读
    references/common/best-practices.md
    - 质量标准
  3. 阅读对应技术的
    rules.md
    文件

Run E2E Tests

运行E2E测试

Workflow: Running E2E Test
  1. Verify Docker infrastructure is running
  2. Run tests sequentially with
    npm run test:e2e > /tmp/e2e-${E2E_SESSION}-output.log 2>&1
  3. Follow failure protocol if tests fail
工作流运行E2E测试
  1. 验证Docker基础设施是否正常运行
  2. 按顺序运行测试:
    npm run test:e2e > /tmp/e2e-${E2E_SESSION}-output.log 2>&1
  3. 如果测试失败,执行失败处理流程

Debug Failing Tests

调试失败的测试

Workflow: Debugging E2E Test
  1. Read
    references/common/debugging.md
  2. Create
    /tmp/e2e-${E2E_SESSION}-failures.md
    tracking file
  3. Fix ONE test at a time
工作流调试E2E测试
  1. 阅读
    references/common/debugging.md
  2. 创建跟踪文件
    /tmp/e2e-${E2E_SESSION}-failures.md
  3. 一次只修复一个测试

Optimize Test Performance

优化测试性能

Workflow: Optimize E2E Test
  1. Read
    references/common/best-practices.md
    - Performance patterns
  2. Read
    references/kafka/performance.md
    for Kafka tests
  3. Measure baseline before making changes
工作流优化E2E测试
  1. 阅读
    references/common/best-practices.md
    - 性能优化模式
  2. 如果是Kafka测试,阅读
    references/kafka/performance.md
  3. 在修改前先测量基准性能

Examples

示例

  • Read
    references/common/examples.md
    for general patterns
  • Read technology-specific
    examples.md
    for detailed scenarios

  • 阅读
    references/common/examples.md
    获取通用模式示例
  • 阅读对应技术的
    examples.md
    获取详细场景示例

Core Principles

核心原则

0. Context Efficiency (Temp File Output)

0. 上下文效率(临时文件输出)

ALWAYS redirect E2E test output to temp files, NOT console. E2E output is verbose and bloats agent context.
IMPORTANT: Redirect output to temp files only (NO console output). Use unique session ID to prevent conflicts.
bash
undefined
务必将E2E测试输出重定向到临时文件,而非控制台。E2E输出内容冗长,会占用大量Agent上下文。
重要提示:仅将输出重定向到临时文件(禁止控制台输出)。使用唯一会话ID避免冲突。
bash
undefined

Generate unique session ID at start of debugging session

在调试会话开始时生成唯一会话ID

export E2E_SESSION=$(date +%s)-$$
export E2E_SESSION=$(date +%s)-$$

Standard pattern - redirect to file only (no console output)

标准写法 - 仅重定向到文件(无控制台输出)

npm run test:e2e > /tmp/e2e-${E2E_SESSION}-output.log 2>&1
npm run test:e2e > /tmp/e2e-${E2E_SESSION}-output.log 2>&1

Read summary only (last 50 lines)

仅查看摘要(最后50行)

tail -50 /tmp/e2e-${E2E_SESSION}-output.log
tail -50 /tmp/e2e-${E2E_SESSION}-output.log

Get failure details

获取失败详情

grep -B 2 -A 15 "FAIL|✕" /tmp/e2e-${E2E_SESSION}-output.log
grep -B 2 -A 15 "FAIL|✕" /tmp/e2e-${E2E_SESSION}-output.log

Cleanup when done

完成后清理文件

rm -f /tmp/e2e-${E2E_SESSION}-.log /tmp/e2e-${E2E_SESSION}-.md

**Temp Files** (with `${E2E_SESSION}` unique per agent):
- `/tmp/e2e-${E2E_SESSION}-output.log` - Full test output
- `/tmp/e2e-${E2E_SESSION}-failures.log` - Filtered failure output
- `/tmp/e2e-${E2E_SESSION}-failures.md` - Tracking file for one-by-one fixing
- `/tmp/e2e-${E2E_SESSION}-debug.log` - Debug runs
- `/tmp/e2e-${E2E_SESSION}-verify.log` - Verification runs
rm -f /tmp/e2e-${E2E_SESSION}-.log /tmp/e2e-${E2E_SESSION}-.md

**临时文件**(每个Agent的`${E2E_SESSION}`唯一):
- `/tmp/e2e-${E2E_SESSION}-output.log` - 完整测试输出
- `/tmp/e2e-${E2E_SESSION}-failures.log` - 过滤后的失败输出
- `/tmp/e2e-${E2E_SESSION}-failures.md` - 逐个修复的跟踪文件
- `/tmp/e2e-${E2E_SESSION}-debug.log` - 调试运行日志
- `/tmp/e2e-${E2E_SESSION}-verify.log` - 验证运行日志

1. Real Infrastructure

1. 真实基础设施

Test against actual services via Docker. Never mock databases or message brokers for E2E tests.
通过Docker测试真实服务。E2E测试中绝不模拟数据库或消息队列。

2. GWT Pattern (Mandatory)

2. GWT模式(强制性)

ALL E2E tests MUST follow Given-When-Then:
typescript
it('should create user and return 201', async () => {
  // GIVEN: Valid user data
  const userData = { email: 'test@example.com', name: 'Test' };

  // WHEN: Creating user
  const response = await request(httpServer)
    .post('/users')
    .send(userData)
    .expect(201);

  // THEN: User created with correct data
  expect(response.body.data.email).toBe('test@example.com');
});
所有E2E测试必须遵循Given-When-Then模式:
typescript
it('should create user and return 201', async () => {
  // GIVEN: 合法的用户数据
  const userData = { email: 'test@example.com', name: 'Test' };

  // WHEN: 创建用户
  const response = await request(httpServer)
    .post('/users')
    .send(userData)
    .expect(201);

  // THEN: 用户创建成功且数据正确
  expect(response.body.data.email).toBe('test@example.com');
});

3. Test Isolation

3. 测试隔离

Each test MUST be independent:
  • Clean database state in
    beforeEach
  • Use unique identifiers (consumer groups, topics)
  • Wait for async operations to complete
每个测试必须独立:
  • beforeEach
    中清理数据库状态
  • 使用唯一标识符(消费者组、主题)
  • 等待异步操作完成

4. Specific Assertions

4. 精准断言

Assert exact values, not just existence:
typescript
// WRONG
expect(response.body.data).toBeDefined();

// CORRECT
expect(response.body).toMatchObject({
  code: 'SUCCESS',
  data: { email: 'test@example.com', name: 'Test' }
});

断言具体值,而非仅判断存在性:
typescript
// 错误写法
expect(response.body.data).toBeDefined();

// 正确写法
expect(response.body).toMatchObject({
  code: 'SUCCESS',
  data: { email: 'test@example.com', name: 'Test' }
});

Project Structure

项目结构

project-root/
├── src/
├── test/
│   ├── e2e/
│   │   ├── feature.e2e-spec.ts
│   │   ├── setup.ts
│   │   └── helpers/
│   │       ├── test-app.helper.ts
│   │       ├── postgres.helper.ts
│   │       ├── mongodb.helper.ts
│   │       ├── redis.helper.ts
│   │       └── kafka.helper.ts
│   └── jest-e2e.config.ts
├── docker-compose.e2e.yml
├── .env.e2e
└── package.json

project-root/
├── src/
├── test/
│   ├── e2e/
│   │   ├── feature.e2e-spec.ts
│   │   ├── setup.ts
│   │   └── helpers/
│   │       ├── test-app.helper.ts
│   │       ├── postgres.helper.ts
│   │       ├── mongodb.helper.ts
│   │       ├── redis.helper.ts
│   │       └── kafka.helper.ts
│   └── jest-e2e.config.ts
├── docker-compose.e2e.yml
├── .env.e2e
└── package.json

Essential Jest Configuration

必备Jest配置

typescript
// test/jest-e2e.config.ts
const config: Config = {
  preset: 'ts-jest',
  testEnvironment: 'node',
  testMatch: ['**/*.e2e-spec.ts'],
  testTimeout: 25000,
  maxWorkers: 1,           // CRITICAL: Sequential execution
  clearMocks: true,
  forceExit: true,
  detectOpenHandles: true,
};

typescript
// test/jest-e2e.config.ts
const config: Config = {
  preset: 'ts-jest',
  testEnvironment: 'node',
  testMatch: ['**/*.e2e-spec.ts'],
  testTimeout: 25000,
  maxWorkers: 1,           // 关键:按顺序执行
  clearMocks: true,
  forceExit: true,
  detectOpenHandles: true,
};

Technology-Specific Timeouts

各技术的超时设置

TechnologyWait TimeStrategy
Kafka10-20s max (polling)Smart polling with 50ms intervals
PostgreSQL<1sDirect queries
MongoDB<1sDirect queries
Redis<100msIn-memory operations
External API1-5sNetwork latency

技术等待时间策略
Kafka最长10-20秒(轮询)50ms间隔的智能轮询
PostgreSQL<1秒直接查询
MongoDB<1秒直接查询
Redis<100ms内存操作
外部API1-5秒考虑网络延迟

Failure Resolution Protocol

失败处理流程

CRITICAL: Fix ONE test at a time. NEVER run full suite repeatedly while fixing.
When E2E tests fail:
  1. Initialize session (once at start):
    bash
    export E2E_SESSION=$(date +%s)-$$
  2. Create tracking file:
    /tmp/e2e-${E2E_SESSION}-failures.md
    with all failing tests
  3. Select ONE failing test - work on only this test
  4. Run ONLY that test (never full suite):
    bash
    npm run test:e2e -- -t "test name" > /tmp/e2e-${E2E_SESSION}-debug.log 2>&1
    tail -50 /tmp/e2e-${E2E_SESSION}-debug.log
  5. Fix the issue - analyze error, make targeted fix
  6. Verify fix - run same test 3-5 times:
    bash
    for i in {1..5}; do npm run test:e2e -- -t "test name" > /tmp/e2e-${E2E_SESSION}-run$i.log 2>&1 && echo "Run $i: PASS" || echo "Run $i: FAIL"; done
  7. Mark as FIXED in tracking file
  8. Move to next failing test - repeat steps 3-7
  9. Run full suite ONLY ONCE after ALL individual tests pass
  10. Cleanup:
    rm -f /tmp/e2e-${E2E_SESSION}-*.log /tmp/e2e-${E2E_SESSION}-*.md
WHY: Running full suite wastes time and context. Each failing test pollutes output, making debugging harder.

关键提示:一次只修复一个测试。修复过程中绝不重复运行完整测试套件。
当E2E测试失败时:
  1. 初始化会话(仅在开始时执行一次):
    bash
    export E2E_SESSION=$(date +%s)-$$
  2. 创建跟踪文件
    /tmp/e2e-${E2E_SESSION}-failures.md
    ,记录所有失败的测试
  3. 选择一个失败的测试 - 仅处理该测试
  4. 仅运行该测试(绝不运行完整套件):
    bash
    npm run test:e2e -- -t "test name" > /tmp/e2e-${E2E_SESSION}-debug.log 2>&1
    tail -50 /tmp/e2e-${E2E_SESSION}-debug.log
  5. 修复问题 - 分析错误,进行针对性修复
  6. 验证修复效果 - 重复运行该测试3-5次:
    bash
    for i in {1..5}; do npm run test:e2e -- -t "test name" > /tmp/e2e-${E2E_SESSION}-run$i.log 2>&1 && echo "Run $i: PASS" || echo "Run $i: FAIL"; done
  7. 在跟踪文件中标记为已修复
  8. 处理下一个失败的测试 - 重复步骤3-7
  9. 仅当所有单个测试都通过后,才运行一次完整套件
  10. 清理文件
    rm -f /tmp/e2e-${E2E_SESSION}-*.log /tmp/e2e-${E2E_SESSION}-*.md
原因:运行完整套件会浪费时间和上下文。每个失败的测试都会污染输出,增加调试难度。

Common Patterns

通用模式

Database Cleanup (PostgreSQL/MongoDB)

数据库清理(PostgreSQL/MongoDB)

typescript
beforeEach(async () => {
  await new Promise(r => setTimeout(r, 500)); // Wait for in-flight
  await repository.clear();  // PostgreSQL
  // OR
  await model.deleteMany({}); // MongoDB
});
typescript
beforeEach(async () => {
  await new Promise(r => setTimeout(r, 500)); // 等待未完成的操作
  await repository.clear();  // PostgreSQL
  // 或者
  await model.deleteMany({}); // MongoDB
});

Kafka Test Helper Pattern

Kafka测试辅助工具模式

typescript
// Use pre-subscription + buffer clearing (NOT fromBeginning: true)
const kafkaHelper = new KafkaTestHelper();
await kafkaHelper.subscribeToTopic(outputTopic, false);
// In beforeEach: kafkaHelper.clearMessages(outputTopic);
typescript
// 使用预订阅 + 缓冲区清理(不要用fromBeginning: true)
const kafkaHelper = new KafkaTestHelper();
await kafkaHelper.subscribeToTopic(outputTopic, false);
// 在beforeEach中:kafkaHelper.clearMessages(outputTopic);

Redis Cleanup

Redis清理

typescript
beforeEach(async () => {
  await redis.flushdb();
});
typescript
beforeEach(async () => {
  await redis.flushdb();
});

External API Mock (MSW)

外部API模拟(MSW)

typescript
mockServer.use(
  http.post('https://api.external.com/endpoint', () => {
    return HttpResponse.json({ status: 'success' });
  })
);
typescript
mockServer.use(
  http.post('https://api.external.com/endpoint', () => {
    return HttpResponse.json({ status: 'success' });
  })
);

Async Event Verification (Kafka)

异步事件验证(Kafka)

typescript
// Use smart polling instead of fixed waits
await kafkaHelper.publishEvent(inputTopic, event, event.id);
const messages = await kafkaHelper.waitForMessages(outputTopic, 1, 20000);
expect(messages[0].value).toMatchObject({ id: event.id });

typescript
// 用智能轮询替代固定等待
await kafkaHelper.publishEvent(inputTopic, event, event.id);
const messages = await kafkaHelper.waitForMessages(outputTopic, 1, 20000);
expect(messages[0].value).toMatchObject({ id: event.id });

Debugging Commands

调试命令

All commands redirect output to temp files only (no console output).
bash
undefined
所有命令仅将输出重定向到临时文件(无控制台输出)。
bash
undefined

Initialize session (once at start)

初始化会话(仅在开始时执行一次)

export E2E_SESSION=$(date +%s)-$$
export E2E_SESSION=$(date +%s)-$$

Run specific test (no console output)

运行指定测试(无控制台输出)

npm run test:e2e -- -t "should create user" > /tmp/e2e-${E2E_SESSION}-output.log 2>&1 && tail -50 /tmp/e2e-${E2E_SESSION}-output.log
npm run test:e2e -- -t "should create user" > /tmp/e2e-${E2E_SESSION}-output.log 2>&1 && tail -50 /tmp/e2e-${E2E_SESSION}-output.log

Run specific file

运行指定文件

npm run test:e2e -- test/e2e/user.e2e-spec.ts > /tmp/e2e-${E2E_SESSION}-output.log 2>&1 && tail -50 /tmp/e2e-${E2E_SESSION}-output.log
npm run test:e2e -- test/e2e/user.e2e-spec.ts > /tmp/e2e-${E2E_SESSION}-output.log 2>&1 && tail -50 /tmp/e2e-${E2E_SESSION}-output.log

Run full suite

运行完整套件

npm run test:e2e > /tmp/e2e-${E2E_SESSION}-output.log 2>&1 && tail -50 /tmp/e2e-${E2E_SESSION}-output.log
npm run test:e2e > /tmp/e2e-${E2E_SESSION}-output.log 2>&1 && tail -50 /tmp/e2e-${E2E_SESSION}-output.log

Get failure details from last run

从上次运行结果中获取失败详情

grep -B 2 -A 15 "FAIL|✕" /tmp/e2e-${E2E_SESSION}-output.log
grep -B 2 -A 15 "FAIL|✕" /tmp/e2e-${E2E_SESSION}-output.log

Debug with breakpoints (requires console for interactive debugging)

使用断点调试(需要控制台进行交互式调试)

node --inspect-brk node_modules/.bin/jest --config test/jest-e2e.config.ts --runInBand
node --inspect-brk node_modules/.bin/jest --config test/jest-e2e.config.ts --runInBand

View application logs (limited)

查看应用日志(有限内容)

tail -100 logs/e2e-test.log grep -i error logs/e2e-test.log | tail -50
tail -100 logs/e2e-test.log grep -i error logs/e2e-test.log | tail -50

Cleanup session files

清理会话文件

rm -f /tmp/e2e-${E2E_SESSION}-.log /tmp/e2e-${E2E_SESSION}-.md

---
rm -f /tmp/e2e-${E2E_SESSION}-.log /tmp/e2e-${E2E_SESSION}-.md

---

Anti-Patterns to Avoid

需要避免的反模式

  1. Multiple WHEN actions - Split into separate tests
  2. Conditional assertions - Create deterministic test cases
  3. Shared state between tests - Clean in beforeEach
  4. Mocking databases - Use real connections
  5. Skipping cleanup - Always clean before AND after
  6. Fixing multiple tests at once - Fix one at a time
  7. Generic assertions - Assert specific values
  8. fromBeginning: true for Kafka - Use pre-subscription + buffer clearing
  1. 多个WHEN操作 - 拆分为独立测试
  2. 条件断言 - 创建确定性的测试用例
  3. 测试间共享状态 - 在beforeEach中清理状态
  4. 模拟数据库 - 使用真实连接
  5. 跳过清理步骤 - 始终在测试前后进行清理
  6. 同时修复多个测试 - 一次只修复一个
  7. 通用断言 - 断言具体值
  8. Kafka使用fromBeginning: true - 使用预订阅 + 缓冲区清理