Using TEA with Existing Tests (Brownfield)
Using TEA with Existing Tests (Brownfield)
Section titled âUsing TEA with Existing Tests (Brownfield)âUse TEA on brownfield projects (existing codebases with legacy tests) to establish coverage baselines, identify gaps, and improve test quality without starting from scratch.
When to Use This
Section titled âWhen to Use Thisâ- Existing codebase with some tests already written
- Legacy test suite needs quality improvement
- Adding features to existing application
- Need to understand current test coverage
- Want to prevent regression as you add features
Prerequisites
Section titled âPrerequisitesâ- Existing codebase with tests (even if incomplete or low quality)
- Tests run successfully (or at least can be executed)
Note: If your codebase is completely undocumented, run document-project first to create baseline documentation. It is a BMM workflow that ships with the BMad Method module, not with TEA.
Brownfield Strategy
Section titled âBrownfield StrategyâPhase 1: Establish Baseline
Section titled âPhase 1: Establish BaselineâUnderstand what you have before changing anything.
Step 1: Baseline Coverage with trace
Section titled âStep 1: Baseline Coverage with traceâRun the trace workflow and select Phase 1 (Requirements Traceability):
/bmad-testarch-traceProvide:
- Existing requirements docs (PRD, user stories, feature specs)
- Test location (
tests/or wherever tests live) - Focus areas (specific features if large codebase)
Output: traceability-matrix.md showing:
- Which requirements have tests
- Which requirements lack coverage
- Coverage classification (FULL/PARTIAL/NONE)
- Gap prioritization
Example Baseline:
# Baseline Coverage (Before Improvements)
**Total Requirements:** 50**Full Coverage:** 15 (30%)**Partial Coverage:** 20 (40%)**No Coverage:** 15 (30%)
**By Priority:**
- P0: 50% coverage (5/10) â Critical gap- P1: 40% coverage (8/20) â ď¸ Needs improvement- P2: 20% coverage (2/10) â
AcceptableThis baseline becomes your improvement target.
Step 2: Quality Audit with test-review
Section titled âStep 2: Quality Audit with test-reviewâRun the test review workflow and answer tests/ when it asks for scope:
/bmad-testarch-test-reviewOutput: test-review.md with quality score and issues.
Common Brownfield Issues:
- Hard waits everywhere (
page.waitForTimeout(5000)) - Fragile CSS selectors (
.class > div:nth-child(3)) - No test isolation (tests depend on execution order)
- Try-catch for flow control
- Tests donât clean up (leave test data in DB)
Example Baseline Quality:
# Quality Score: 55/100
**Critical Issues:** 12
- 8 hard waits- 4 conditional flow control
**Recommendations:** 25
- Extract fixtures- Improve selectors- Add network assertionsThis shows where to focus improvement efforts.
Phase 2: Prioritize Improvements
Section titled âPhase 2: Prioritize ImprovementsâDonât try to fix everything at once.
Focus on Critical Path First
Section titled âFocus on Critical Path FirstâPriority 1: P0 Requirements. Goal: P0 coverage at 100%.
- Identify P0 requirements with no tests (from the trace matrix)
- Run
/bmad-testarch-automateto generate tests for the missing P0 scenarios - Fix the critical quality issues those tests carry (from the test-review report)
Priority 2: Fix Flaky Tests. Goal: eliminate flakiness.
- Identify tests with hard waits (from the test-review report)
- Replace them with network-first patterns
- Run burn-in loops to verify stability
Example Modernization:
Before (Flaky - Hard Waits):
test('checkout completes', async ({ page }) => { await page.click('button[name="checkout"]'); await page.waitForTimeout(5000); // â Flaky await expect(page.locator('.confirmation')).toBeVisible();});After (Network-First - Vanilla):
test('checkout completes', async ({ page }) => { const checkoutPromise = page.waitForResponse((resp) => resp.url().includes('/api/checkout') && resp.ok()); await page.click('button[name="checkout"]'); await checkoutPromise; // â
Deterministic await expect(page.locator('.confirmation')).toBeVisible();});After (With Playwright Utils - Cleaner API):
import { test } from '@seontechnologies/playwright-utils/intercept-network-call/fixtures';import { expect } from '@playwright/test';
test('checkout completes', async ({ page, interceptNetworkCall }) => { // Use interceptNetworkCall for cleaner network interception const checkoutCall = interceptNetworkCall({ method: 'POST', url: '**/api/checkout', });
await page.click('button[name="checkout"]');
// Wait for response (automatic JSON parsing) const { status, responseJson: order } = await checkoutCall;
// Validate API response expect(status).toBe(200); expect(order.status).toBe('confirmed');
// Validate UI await expect(page.locator('.confirmation')).toBeVisible();});Playwright Utils Benefits:
interceptNetworkCallfor cleaner network interception- Automatic JSON parsing (
responseJsonready to use) - No manual
await response.json() - Glob pattern matching (
**/api/checkout) - Cleaner, more maintainable code
For automatic error detection, use network-error-monitor fixture separately. See Integrate Playwright Utils.
Priority 3: P1 Requirements. Goal: P1 coverage at 80% or above.
- Generate tests for the highest-risk P1 gaps
- Improve test quality incrementally
Create Improvement Roadmap
Section titled âCreate Improvement Roadmapâ# Test Improvement Roadmap
## Week 1: Critical Path (P0)
- [ ] Add 5 missing P0 tests (Epic 1: Auth)- [ ] Fix 8 hard waits in auth tests- [ ] Verify P0 coverage = 100%
## Week 2: Flakiness
- [ ] Replace all hard waits with network-first- [ ] Fix conditional flow control- [ ] Run burn-in loops (target: 0 failures in 10 runs)
## Week 3: High-Value Coverage (P1)
- [ ] Add 10 missing P1 tests- [ ] Improve selector resilience- [ ] P1 coverage target: 80%
## Week 4: Quality Polish
- [ ] Extract fixtures for common patterns- [ ] Add network assertions- [ ] Quality score target: 75+Phase 3: Incremental Improvement
Section titled âPhase 3: Incremental ImprovementâApply TEA workflows to new work while improving legacy tests.
For New Features (Greenfield Within Brownfield)
Section titled âFor New Features (Greenfield Within Brownfield)âUse the full TEA workflow:
/bmad-testarch-test-design(epic-level) to plan tests for the new feature/bmad-testarch-atddto generate failing tests first- Implement the feature
/bmad-testarch-automateto expand coverage/bmad-testarch-test-reviewto check quality
Benefits:
- New code has high-quality tests from day one
- Gradually raises overall quality
- Team learns good patterns
For Bug Fixes (Regression Prevention)
Section titled âFor Bug Fixes (Regression Prevention)âAdd regression tests:
- Reproduce the bug with a failing test
- Fix the bug
- Verify the test passes
- Run
/bmad-testarch-test-reviewon the regression test - Add it to the regression suite
For Refactoring (Regression Safety)
Section titled âFor Refactoring (Regression Safety)âBefore refactoring:
- Run
/bmad-testarch-tracefor a baseline and note the coverage percentage - Refactor the code
- Run
/bmad-testarch-traceagain; no priorityâs coverage should have decreased
Phase 4: Continuous Improvement
Section titled âPhase 4: Continuous ImprovementâTrack improvement over time.
Quarterly Quality Audits
Section titled âQuarterly Quality Auditsâ| Quarter | Coverage | Quality score | Flakiness |
|---|---|---|---|
| Q1 (baseline) | 30% | 55/100 | 15% fail rate |
| Q2 target | 50% (focus on P0) | 65/100 | 5% |
| Q3 target | 70% | 75/100 | 1% |
| Q4 target | 85% | 85/100 | <0.5% |
Brownfield-Specific Tips
Section titled âBrownfield-Specific TipsâDonât Rewrite Everything
Section titled âDonât Rewrite EverythingâCommon mistake: âOur tests are bad, letâs delete them all and start over.â
Better approach: a rewrite risks losing coverage you already have. Instead:
- Keep tests that work, even imperfect ones
- Fix critical quality issues incrementally
- Add tests for the gaps
- Improve gradually
Use Regression Hotspots
Section titled âUse Regression HotspotsâIdentify regression-prone areas:
## Regression Hotspots
**Based on:**
- Bug reports (last 6 months)- Customer complaints- Code complexity (cyclomatic complexity >10)- Frequent changes (git log analysis)
**High-Risk Areas:**
1. Authentication flow (12 bugs in 6 months)2. Checkout process (8 bugs)3. Payment integration (6 bugs)
**Test Priority:**
- Add regression tests for these areas FIRST- Ensure P0 coverage before touching codeQuarantine Flaky Tests
Section titled âQuarantine Flaky TestsâDonât let flaky tests block improvement:
// Mark flaky tests with .skip temporarilytest.skip('flaky test - needs fixing', async ({ page }) => { // TODO: Fix hard wait on line 45 // TODO: Add network-first pattern});Track quarantined tests:
# Quarantined Tests
| Test | Reason | Owner | Target Fix Date || ------------------- | -------------------------- | -------- | --------------- || checkout.spec.ts:45 | Hard wait causes flakiness | QA Team | 2026-01-20 || profile.spec.ts:28 | Conditional flow control | Dev Team | 2026-01-25 |Fix systematically:
- Donât accumulate quarantined tests
- Set deadlines for fixes
- Review quarantine list weekly
Migrate One Directory at a Time
Section titled âMigrate One Directory at a TimeâLarge test suite? Improve incrementally:
Take one directory per week (tests/auth/, then tests/api/, then tests/e2e/), running the same loop on each:
- Run
/bmad-testarch-test-reviewand give that directory as the scope - Fix the critical issues
- Re-review
- Mark the directory as âmodernizedâ
Benefits:
- Focused improvement
- Visible progress
- Team learns patterns
- Lower risk
Document Migration Status
Section titled âDocument Migration StatusâTrack which tests are modernized:
# Test Suite Status
| Directory | Tests | Quality Score | Status | Notes || ------------------ | ----- | ------------- | -------------- | -------------- || tests/auth/ | 15 | 85/100 | â
Modernized | Week 1 cleanup || tests/api/ | 32 | 78/100 | â ď¸ In Progress | Week 2 || tests/e2e/ | 28 | 62/100 | â Legacy | Week 3 planned || tests/integration/ | 12 | 45/100 | â Legacy | Week 4 planned |
**Legend:**
- â
Modernized: Quality >80, no critical issues- â ď¸ In Progress: Active improvement- â Legacy: UntouchedCommon Brownfield Challenges
Section titled âCommon Brownfield ChallengesââWe Donât Know What Tests Coverâ
Section titled ââWe Donât Know What Tests CoverââProblem: No documentation, unclear what tests do.
Solution:
- Run
/bmad-testarch-trace; TEA analyzes the tests and maps them to requirements - Review the traceability matrix
- Document the findings
- Use it as your improvement baseline
TEA reverse-engineers test coverage even without documentation.
âTests Are Too Brittle to Touchâ
Section titled ââTests Are Too Brittle to TouchââProblem: Afraid to modify tests (might break them).
Solution: small changes carry small risk.
- Run the tests and capture current behavior as the baseline
- Make one small improvement, such as removing a single hard wait
- Run the tests again
- If they still pass, continue; if they fail, investigate before going further
âNo One Knows How to Run Testsâ
Section titled ââNo One Knows How to Run TestsââProblem: Test documentation is outdated or missing.
Solution:
- Document manually, or ask TEA to analyze the test structure for you
- Create
tests/README.mdcovering how to install dependencies, how to run the tests (npx playwright test,npm test, or whatever your runner is), what each test directory contains, and common troubleshooting - Commit it for the team
Note: framework scaffolds a new test setup. For brownfield, document what you already have instead.
âTests Take Hours to Runâ
Section titled ââTests Take Hours to RunââProblem: Full test suite takes 4+ hours.
Solution: sharding plus selective testing takes a 4-hour sequential suite to about 15 minutes.
- Configure parallel execution (shard tests across workers)
- Add selective testing so PRs run only affected tests
- Run the full suite nightly only
- Optimize slow tests by removing hard waits and improving selectors
How ci helps:
- Scaffolds CI configuration with parallel sharding examples
- Provides selective testing script templates
- Documents burn-in and optimization strategies
- But YOU configure workers, test selection, and optimization
With Playwright Utils burn-in:
- Smart selective testing based on git diff
- Volume control (run percentage of affected tests)
- See Integrate Playwright Utils
âWe Have Tests But They Always Failâ
Section titled ââWe Have Tests But They Always FailââProblem: Tests are so flaky theyâre ignored.
Solution:
- Run
/bmad-testarch-test-reviewto identify the flakiness patterns - Fix the top 5 flaky tests, which carry most of the impact
- Quarantine the rest
- Re-enable them as you fix them
Brownfield TEA Workflow
Section titled âBrownfield TEA WorkflowâRecommended Sequence
Section titled âRecommended Sequenceâdocument-project, prd, and architecture are BMM workflows that ship with the BMad Method module, not with TEA. Every /bmad-testarch-* command below is TEA. On Codex, swap the leading / for $.
| Stage | Command | Purpose |
|---|---|---|
| 1. Documentation (if needed) | document-project (BMM) | Baseline docs for an undocumented codebase |
| 2. Baseline (Phase 2) | /bmad-testarch-trace, Phase 1 | Coverage baseline |
| 2. Baseline (Phase 2) | /bmad-testarch-test-review | Quality baseline |
| 3. Planning (Phase 2-3) | prd, architecture (BMM) | Document requirements and architecture if missing |
| 3. Planning (Phase 2-3) | /bmad-testarch-test-design, system-level | Testability review |
| 4. Infrastructure (Phase 3) | /bmad-testarch-framework | Modernize the test framework, if needed |
| 4. Infrastructure (Phase 3) | /bmad-testarch-ci | Set up or improve CI/CD |
| 5. Per epic (Phase 4) | /bmad-testarch-test-design, epic-level | Focus on regression hotspots |
| 5. Per epic (Phase 4) | /bmad-testarch-automate | Add the missing tests |
| 5. Per epic (Phase 4) | /bmad-testarch-test-review | Check quality |
| 5. Per epic (Phase 4) | /bmad-testarch-trace, Phase 1 | Refresh coverage |
| 6. Release gate | /bmad-testarch-nfr | Audit NFR evidence, where evidence exists |
| 6. Release gate | /bmad-testarch-trace, Phase 2 | Gate decision |
Related Guides
Section titled âRelated GuidesâWorkflow Guides:
- How to Run Trace - Baseline coverage analysis
- How to Run Test Review - Quality audit
- How to Run Automate - Fill coverage gaps
- How to Run Test Design - Risk assessment
Customization:
- Integrate Playwright Utils - Modernize tests with utilities
Understanding the Concepts
Section titled âUnderstanding the Conceptsâ- Engagement Models - Brownfield model explained
- Test Quality Standards - What makes tests good
- Network-First Patterns - Fix flakiness
- Risk-Based Testing - Prioritize improvements
Reference
Section titled âReferenceâ- TEA Command Reference - All 9 workflows
- TEA Configuration - Config options
- Knowledge Base Index - Testing patterns
- Glossary - TEA terminology