Test Specialist
Overview
Apply systematic testing methodologies and debugging techniques to JavaScript/TypeScript applications. This skill provides comprehensive testing strategies, bug analysis frameworks, and automated tools for identifying coverage gaps and untested code.
Core Capabilities
1. Writing Test Cases
Write comprehensive tests covering unit, integration, and end-to-end scenarios.
Unit Testing Approach
Structure tests using the AAA pattern (Arrange-Act-Assert):
CODEBLOCK0
Key principles:
- - Test one behavior per test
- Cover happy path, edge cases, and error conditions
- Use descriptive test names that explain the scenario
- Keep tests independent and isolated
Integration Testing Approach
Test how components work together, including database, API, and service interactions:
CODEBLOCK1
End-to-End Testing Approach
Test complete user workflows using tools like Playwright or Cypress:
CODEBLOCK2
2. Systematic Bug Analysis
Apply structured debugging methodology to identify and fix issues.
Five-Step Analysis Process
- 1. Reproduction: Reliably reproduce the bug
- Document exact steps to trigger
- Identify required environment/state
- Note expected vs actual behavior
- 2. Isolation: Narrow down the problem
- Binary search through code path
- Create minimal reproduction case
- Remove unrelated dependencies
- 3. Root Cause Analysis: Determine underlying cause
- Trace execution flow
- Check assumptions and preconditions
- Review recent changes (git blame)
- 4. Fix Implementation: Implement solution
- Write failing test first (TDD)
- Implement the fix
- Verify test passes
- 5. Validation: Ensure completeness
- Run full test suite
- Test edge cases
- Verify no regressions
Common Bug Patterns
Race Conditions:
CODEBLOCK3
Null/Undefined Errors:
CODEBLOCK4
Off-by-One Errors:
CODEBLOCK5
3. Identifying Potential Issues
Proactively identify issues before they become bugs.
Security Vulnerabilities
Test for common security issues:
CODEBLOCK6
Performance Issues
Test for performance problems:
CODEBLOCK7
Logic Errors
Use parameterized tests to catch edge cases:
CODEBLOCK8
4. Test Coverage Analysis
Use automated tools to identify gaps in test coverage.
Finding Untested Code
Run the provided script to identify source files without tests:
CODEBLOCK9
The script will:
- - Scan source directory for all code files
- Identify which files lack corresponding test files
- Categorize untested files by type (components, services, utils, etc.)
- Prioritize files that need testing most
Interpretation:
- - API/Services: High priority - test business logic and data operations
- Models: High priority - test data validation and transformations
- Hooks: Medium priority - test stateful behavior
- Components: Medium priority - test complex UI logic
- Utils: Low priority - test as needed for complex functions
Analyzing Coverage Reports
Run the coverage analysis script after generating coverage:
CODEBLOCK10
The script identifies:
- - Files below coverage threshold (default 80%)
- Statement, branch, and function coverage percentages
- Priority files to improve
Coverage targets:
- - Critical paths: 90%+ coverage
- Business logic: 85%+ coverage
- UI components: 75%+ coverage
- Utilities: 70%+ coverage
5. Test Maintenance and Quality
Ensure tests remain valuable and maintainable.
Test Code Quality Principles
DRY (Don't Repeat Yourself):
CODEBLOCK11
Clear test data:
CODEBLOCK12
Avoid test interdependence:
CODEBLOCK13
Workflow Decision Tree
Follow this decision tree to determine the testing approach:
- 1. Adding new functionality?
- Yes → Write tests first (TDD)
- Write failing test
- Implement feature
- Verify test passes
- Refactor
- No → Go to step 2
- 2. Fixing a bug?
- Yes → Apply bug analysis process
- Reproduce the bug
- Write failing test demonstrating bug
- Fix the implementation
- Verify test passes
- No → Go to step 3
- 3. Improving test coverage?
- Yes → Use coverage tools
- Run
find_untested_code.py to identify gaps
- Run
analyze_coverage.py on coverage reports
- Prioritize critical paths
- Write tests for untested code
- No → Go to step 4
- 4. Analyzing code quality?
- Yes → Systematic review
- Check for security vulnerabilities
- Test edge cases and error handling
- Verify performance characteristics
- Review error handling
Testing Frameworks and Tools
Recommended Stack
Unit/Integration Testing:
- - Jest or Vitest for test runner
- Testing Library for React components
- Supertest for API testing
- MSW (Mock Service Worker) for API mocking
E2E Testing:
- - Playwright or Cypress
- Page Object Model pattern
Coverage:
- - Istanbul (built into Jest/Vitest)
- Coverage reports in JSON format
Running Tests
CODEBLOCK14
Reference Documentation
For detailed patterns and techniques, refer to:
- -
references/testing_patterns.md - Comprehensive testing patterns, best practices, and code examples - INLINECODE3 - In-depth bug analysis framework, common bug patterns, and debugging techniques
These references contain extensive examples and advanced techniques. Load them when:
- - Dealing with complex testing scenarios
- Need specific pattern implementations
- Debugging unusual issues
- Seeking best practices for specific situations
Scripts
analyze_coverage.py
Analyze Jest/Istanbul coverage reports to identify gaps:
CODEBLOCK15
Automatically finds common coverage file locations if not specified.
Output:
- - Files below coverage threshold
- Statement, branch, and function coverage percentages
- Priority files to improve
finduntestedcode.py
Find source files without corresponding test files:
CODEBLOCK16
Output:
- - Total source and test file counts
- Test file coverage percentage
- Untested files categorized by type (API, services, components, etc.)
- Recommendations for prioritization
Best Practices Summary
- 1. Write tests first (TDD) when adding new features
- Test behavior, not implementation - tests should survive refactoring
- Keep tests independent - no shared state between tests
- Use descriptive names - test names should explain the scenario
- Cover edge cases - null, empty, boundary values, error conditions
- Mock external dependencies - tests should be fast and reliable
- Maintain high coverage - 80%+ for critical code
- Fix failing tests immediately - never commit broken tests
- Refactor tests - apply same quality standards as production code
- Use tools - automate coverage analysis and gap identification
测试专家
概述
将系统化测试方法和调试技术应用于 JavaScript/TypeScript 应用程序。该技能提供全面的测试策略、错误分析框架以及用于识别覆盖缺口和未测试代码的自动化工具。
核心能力
1. 编写测试用例
编写涵盖单元测试、集成测试和端到端场景的全面测试。
单元测试方法
使用 AAA 模式(Arrange-Act-Assert,即 准备-执行-断言)组织测试:
typescript
describe(ExpenseCalculator, () => {
describe(calculateTotal, () => {
test(正确计算费用总和, () => {
// 准备
const expenses = [
{ amount: 100, category: food },
{ amount: 50, category: transport },
{ amount: 25, category: entertainment }
];
// 执行
const total = calculateTotal(expenses);
// 断言
expect(total).toBe(175);
});
test(处理空费用列表, () => {
expect(calculateTotal([])).toBe(0);
});
test(处理负数金额, () => {
const expenses = [
{ amount: 100, category: food },
{ amount: -50, category: refund }
];
expect(calculateTotal(expenses)).toBe(50);
});
});
});
关键原则:
- - 每个测试只测试一个行为
- 覆盖快乐路径、边界情况和错误条件
- 使用描述性测试名称解释场景
- 保持测试独立且隔离
集成测试方法
测试组件如何协同工作,包括数据库、API 和服务交互:
typescript
describe(ExpenseAPI 集成测试, () => {
beforeAll(async () => {
await database.connect(TESTDBURL);
});
afterAll(async () => {
await database.disconnect();
});
beforeEach(async () => {
await database.clear();
await seedTestData();
});
test(POST /expenses 创建费用并更新总额, async () => {
const response = await request(app)
.post(/api/expenses)
.send({
amount: 50,
category: food,
description: 午餐
})
.expect(201);
expect(response.body).toMatchObject({
id: expect.any(Number),
amount: 50,
category: food
});
// 验证数据库状态
const total = await getTotalExpenses();
expect(total).toBe(50);
});
});
端到端测试方法
使用 Playwright 或 Cypress 等工具测试完整的用户工作流:
typescript
test(用户可以从头到尾跟踪费用, async ({ page }) => {
// 导航到应用
await page.goto(/);
// 添加新费用
await page.click([data-testid=add-expense-btn]);
await page.fill([data-testid=amount], 50.00);
await page.selectOption([data-testid=category], food);
await page.fill([data-testid=description], 午餐);
await page.click([data-testid=submit]);
// 验证费用出现在列表中
await expect(page.locator([data-testid=expense-item])).toContainText(午餐);
await expect(page.locator([data-testid=total])).toContainText($50.00);
});
2. 系统化错误分析
应用结构化的调试方法来识别和修复问题。
五步分析流程
- 1. 复现:可靠地复现错误
- 记录触发错误的确切步骤
- 识别所需的环境/状态
- 记录预期行为与实际行为
- 2. 隔离:缩小问题范围
- 通过代码路径进行二分查找
- 创建最小复现案例
- 移除不相关的依赖
- 3. 根因分析:确定根本原因
- 追踪执行流程
- 检查假设和前置条件
- 审查最近的更改(git blame)
- 4. 修复实施:实现解决方案
- 先编写失败的测试(TDD)
- 实施修复
- 验证测试通过
- 5. 验证:确保完整性
- 运行完整测试套件
- 测试边界情况
- 验证无回归
常见错误模式
竞态条件:
typescript
// 测试并发操作
test(正确处理并发更新, async () => {
const promises = Array.from({ length: 100 }, () =>
incrementExpenseCount()
);
await Promise.all(promises);
expect(getExpenseCount()).toBe(100);
});
空值/未定义错误:
typescript
// 测试空值安全性
test.each([null, undefined, , 0, false])
(处理无效输入: %p, (input) => {
expect(() => processExpense(input)).toThrow(无效的费用);
});
差一错误:
typescript
// 显式测试边界
describe(分页, () => {
test(处理空列表, () => {
expect(paginate([], 1, 10)).toEqual([]);
});
test(处理单个项目, () => {
expect(paginate([item], 1, 10)).toEqual([item]);
});
test(处理包含部分项目的最后一页, () => {
const items = Array.from({ length: 25 }, (_, i) => i);
expect(paginate(items, 3, 10)).toHaveLength(5);
});
});
3. 识别潜在问题
在问题变成错误之前主动识别。
安全漏洞
测试常见安全问题:
typescript
describe(安全性, () => {
test(防止 SQL 注入, async () => {
const malicious = ; DROP TABLE expenses; --;
await expect(
searchExpenses(malicious)
).resolves.not.toThrow();
});
test(清理描述中的 XSS, () => {
const xss = ;
const expense = createExpense({ description: xss });
expect(expense.description).not.toContain(