Review Test Code for Anti-Patterns with AI
Reads a test file and returns a categorized list of anti-patterns: hard sleeps, shared mutable state, weak assertions (`toBeTruthy` instead of `toEqual`), missing teardown, mixed setup/assertion concerns, each with line numbers, severity, and a suggested fix.
When to use it
- PR review of a new test file or suite.
- Auditing an inherited test suite that everyone complains about but no one fixes.
- Teaching engineers what 'bad test code' looks like by showing real examples.
- Standardizing test quality across multiple teams.
The prompt
<role>You are a test code reviewer. You can name anti-patterns by category and you cite line numbers so suggestions are actionable. You distinguish anti-patterns from legitimate exceptions.</role> <context>Common test anti-patterns:- **Hard sleeps**: `waitForTimeout`, `sleep`, `setTimeout` for synchronization- **Shared mutable state**: variables outside test scope; test order dependence- **Weak assertions**: `toBeTruthy` / `toBeDefined` when `toEqual` would be precise- **Missing teardown**: fixtures that don't clean up; tests that pollute next runs- **Mixed concerns**: setup, action, and assertion interleaved instead of arranged (Arrange-Act-Assert)- **God assertions**: one `expect` that checks 10 things; failure unclear- **Test interdependence**: test 2 requires test 1 having run- **Hardcoded values**: magic numbers / strings instead of named constants- **No descriptive names**: `test('test 1')` instead of `test('signs in with valid credentials')`- **Try/catch hiding failures**: caught exception means test still passes</context> <task>For the test file below:1. Identify anti-patterns by category.2. Cite LINE NUMBERS (or "near setup block" if unclear).3. Rate severity: Major (likely cause of test failure / wrong result), Minor (style / maintainability).4. Suggest a concrete fix per anti-pattern.5. Note any patterns that LOOK like anti-patterns but are legitimate (e.g., one intentional sleep waiting for an unsoftenable race).</task> <input>Test file content (with line numbers): {test_code}Framework (Playwright / Jest / Cypress): {framework}</input> <constraints>- LINE NUMBERS required (or explicit "near X" reference).- Categorize each finding by anti-pattern type.- Severity labels: MAJOR / MINOR, no "high/medium/low" or other terms.- Concrete fix per finding, not "improve this".- Distinguish anti-pattern from legitimate exception (rare but possible).</constraints> <output_format>Markdown table: Line | Anti-pattern | Severity | Issue | Suggested fix. Followed by 2-3 bullets on the BIGGEST issue (if a pattern across multiple lines).</output_format> <approach>Before writing, read the entire file once to catch cross-line patterns (e.g., shared state).</approach>## RoleTest code reviewer. Name anti-patterns by category. Cite line numbers. Distinguish anti-patterns from legitimate exceptions. ## ContextCommon anti-patterns:- Hard sleeps (waitForTimeout, sleep)- Shared mutable state (variables outside test scope)- Weak assertions (toBeTruthy instead of toEqual)- Missing teardown- Mixed concerns (no Arrange-Act-Assert)- God assertions (one expect checking 10 things)- Test interdependence- Hardcoded values (magic numbers)- No descriptive names- Try/catch hiding failures ## Task1. Identify anti-patterns by category.2. Cite LINE NUMBERS.3. Severity: MAJOR / MINOR.4. Concrete fix per pattern.5. Note legitimate exceptions if any. ## Input- Test code: {test_code}- Framework: {framework} ## Constraints- Line numbers required.- Categorize per anti-pattern type.- MAJOR / MINOR only (no high/medium/low).- Concrete fix, not "improve this".- Distinguish anti-pattern vs legitimate exception. ## Output formatMarkdown table (Line | Anti-pattern | Severity | Issue | Suggested fix) + 2-3 bullets on the BIGGEST cross-line issue. ## ApproachRead entire file first to catch cross-line patterns.Example
Input
Test file content:
```typescript
1 import { test, expect } from '@playwright/test';
2
3 let token: string;
4 let userId: number;
5
6 test('login', async ({ page }) => {
7 await page.goto('/login');
8 await page.fill('#email', 'test@example.com');
9 await page.fill('#password', '123');
10 await page.click('button');
11 await page.waitForTimeout(3000);
12 token = await page.evaluate(() => localStorage.getItem('token'));
13 expect(token).toBeTruthy();
14 });
15
16 test('fetch profile', async ({ request }) => {
17 const res = await request.get('/api/profile', { headers: { Authorization: `Bearer ${token}` } });
18 const body = await res.json();
19 userId = body.id;
20 expect(body).toBeDefined();
21 });
22
23 test('update profile', async ({ request }) => {
24 try {
25 await request.patch(`/api/users/${userId}`, { data: { name: 'New' } });
26 expect(true).toBe(true);
27 } catch (e) {
28 console.log('error', e);
29 }
30 });
```
Framework: PlaywrightOutput
## Anti-patterns found
| Line | Anti-pattern | Severity | Issue | Suggested fix |
|------|--------------|----------|-------|---------------|
| 3-4 | Shared mutable state | MAJOR | `token` and `userId` are file-scoped; later tests depend on earlier tests setting them. Test order dependency. | Use Playwright fixtures (`test.extend`) or run each test independently with own auth. |
| 6 | Vague test name | MINOR | `'login'` doesn't describe what's being verified. | Rename to `'logs in with valid credentials and stores token'`. |
| 8-10 | Brittle / legacy locators | MINOR | `page.fill('#email')`, `page.click('button')` use the page-level API with CSS selectors; `'button'` matches the first button on the page, whatever it is. | Use locators: `page.getByLabel('Email').fill(...)`, `page.getByRole('button', { name: 'Sign in' }).click()`. |
| 11 | Hard sleep | MAJOR | `waitForTimeout(3000)` masks a race. On slow CI may not be enough; on fast local wastes time. | Replace with `await expect(page).toHaveURL(/\/dashboard/)` or `await page.waitForResponse(...)`. |
| 13 | Weak assertion | MAJOR | `toBeTruthy()` passes for any non-empty string but doesn't verify the token is a JWT or has expected shape. | Use `expect(token).toMatch(/^eyJ/)` (JWT format) or assert specific shape. |
| 16-17 | Test interdependence | MAJOR | `'fetch profile'` requires `'login'` to have run first to populate `token`. If tests reorder or run in parallel, this fails. | Make each test self-contained: log in (or use storage state) in each test. |
| 20 | Weak assertion | MINOR | `expect(body).toBeDefined()` passes if body is any object including `{}`. | Use `expect(body.id).toBe(expectedId)` or `expect(body).toMatchObject({ ... })`. |
| 23-30 | Try/catch hiding failures | MAJOR | If `request.patch` throws, the catch swallows the error and the test passes via `expect(true).toBe(true)`. | Remove try/catch; let errors fail the test. Or use `await expect(...).rejects` if you expect a specific error. |
| 26 | God / placeholder assertion | MAJOR | `expect(true).toBe(true)` is a no-op assertion. The test verifies nothing. | Assert the actual state: verify the response status, body, or downstream state. |
| (file-wide) | Missing teardown | MAJOR | No cleanup of test users, tokens, or profile state after run. Pollutes next test runs. | Add `test.afterEach` to clean up created data, OR seed a fresh user per test. |
## Biggest cross-line issues
- **Test interdependence is the dominant issue**. Tests 1, 2, 3 share state via top-level variables: Playwright runs tests in file order so this currently works, but the moment you parallelize, shard, or run a single test, it breaks. Refactor to make every test self-contained.
- **No teardown anywhere**: three tests create state (login session, profile update) with no cleanup. Pre-existing test users accumulate; future runs are non-deterministic.
- **Multiple weak / no-op assertions** (lines 13, 20, 26): the test suite would currently pass even if all three endpoints returned wrong data. The test was probably written to "exercise the code", not to "verify behavior". Rewrite each test around a specific behavior to verify.Common pitfalls
- Model rewrites the entire test file instead of pinpointing line-level issues. Force table-based findings.
- False positives on legitimate sleeps (rare but exists: e.g., debounce); reviewer must distinguish.
- Cross-line patterns (shared state, missing teardown) get listed as 10 individual issues; cluster them.
- Severity defaults to all MAJOR. Force discrimination: style issues are MINOR.
Tips
- Run this BEFORE merging, not after. Anti-patterns compound: a test using shared state spreads the pattern to neighbors.
- Pair with `refactor-flaky-test` when an anti-pattern (hard sleep) is the actual root cause of a flake.
- Use this as part of PR template: link to the prompt as a self-review tool.
- Re-run quarterly on existing test suites; debt accumulates faster than you think.
FAQ
Which anti-pattern hurts most in practice?
Test interdependence: it scales worst. A suite with shared state cannot parallelize, cannot shard, and individual test runs become unreliable. Fixing it requires touching every test.
Can I automate this in CI?
Partially: ESLint rules cover some (`no-magic-numbers`, `no-shared-state`). The pattern-based detection (god assertion, weak assertion) is harder to lint reliably. Use this prompt for the harder patterns; ESLint for the simple ones.
How is this different from `test-code-quality-checklist`?
This prompt finds problems in a specific file ("what's wrong here?"). The checklist verifies general best practices ("is this well-tested?"). Use both: the checklist for breadth, this prompt for depth.
What about false positives on legitimate sleeps?
Rare but real: e.g., waiting on a debounced search input. Output should flag them as 'legitimate exception' with reasoning. Don't blindly remove them.