Test Data, Mocks, Flakiness, CI & Performance Regression
A test suite can contain correct assertions and still be untrustworthy because its infrastructure is unstable.
Production-quality testing requires engineering around:
state
time
randomness
network
parallelism
external services
CI evidence
1. Every test owns its stateβ
A strong default:
arrange isolated state
β execute behaviour
β assert
β cleanup or discard environment
Avoid hidden dependence on suite order.
2. Test data buildersβ
Prefer intention-revealing builders:
const user = makeUser({ role: 'member', tenantId: tenant.id })
const invoice = makeInvoice({ tenantId: tenant.id, status: 'open' })
Builders should provide safe defaults while letting each test show the fields relevant to the scenario.
3. Avoid mystery fixturesβ
Weak:
seed-v14-final-final.json
where hundreds of records exist and no test explains which ones matter.
Better:
small scenario fixture
explicit relationship
unique test namespace
4. Database isolation strategiesβ
Options include:
transaction rollback
schema/database per worker
container per suite
unique tenant prefix + cleanup
snapshot/restore
Pick based on database/runtime constraints.
Parallel tests must not mutate the same rows unless concurrency is the behaviour under test.
5. Stable IDsβ
Random UUIDs are useful for isolation but can make diagnostics hard.
Consider a deterministic namespace:
test name + worker id + generated suffix
Never use predictable production identifiers as a security assumption.
6. Control timeβ
Tests involving:
session expiry
cache age
booking windows
rate limits
relative dates
scheduled jobs
should use fake clocks or injectable clocks where possible.
Do not sleep until a token βreally expires.β
7. Control randomnessβ
Randomness can be injected:
function chooseVariant(random = Math.random) { ... }
Tests can provide deterministic values.
For property-based tests, log the failing seed so the failure can be reproduced.
8. External-service test pyramidβ
For a provider:
unit β mock adapter boundary
contract/integration β provider sandbox or fake server
E2E β representative sandbox flow
Examples:
payments
email
SMS
OAuth provider
storage
search engine
Do not make every PR depend on the public internet.
9. Contract fixturesβ
Record or hand-build representative provider payloads with sensitive data removed.
Version them when the provider schema changes.
Test:
required fields
unknown fields
missing optional fields
new enum/value behaviour
signature/raw-body contract where applicable
10. Mock the boundary you ownβ
If your code owns:
PaymentGateway interface
mock that interface for domain tests.
If the HTTP client adapter is under test, do not mock the adapter itself; fake the HTTP service.
11. Flake taxonomyβ
A flaky test usually belongs to a class:
timing/race
shared state
network/provider
resource exhaustion
unstable selector
environment mismatch
clock/timezone
random data
order dependence
browser rendering
Classify before βfixing.β
12. Retries are diagnostics, not repairsβ
A CI retry can reveal intermittent failures and reduce transient noise, but it must not hide product races.
Track:
first-attempt failure rate
retry pass rate
test name
release
worker/browser
Quarantine only with an owner and repair deadline.
13. Do not solve flake with sleepsβ
Bad:
await page.waitForTimeout(2000)
Better:
wait for semantic UI condition
wait for known request/state transition
control dependency completion
A sleep adds latency and still fails on slower CI.
14. Parallelism exposes architecture problemsβ
A suite that only passes serially may have:
global mutable fixtures
shared user account
shared file path
shared cache keys
non-isolated database rows
fixed ports
Use parallelism deliberately and remove accidental global state.
15. CI layersβ
A practical pull-request pipeline:
lint/typecheck
β unit/component
β integration
β production build
β critical E2E
Heavy cross-browser, load, or full regression suites can run on merge/nightly/release according to risk.
16. Fail fast without hiding evidenceβ
Parallel CI jobs shorten feedback, but preserve artifacts from every failed job.
Useful artifacts:
JUnit/test report
coverage
Playwright trace
screenshots
server logs
browser console
build log
performance output
17. Environment variables in testsβ
Use dedicated test configuration.
Never expose production secrets to untrusted PR workflows.
For fork PRs:
run secret-free tests
skip/replace protected integration jobs
run protected jobs only in trusted context
Security of CI credentials is part of test architecture.
18. Cache dependencies carefullyβ
CI dependency caches can speed builds, but do not cache mutable test state accidentally.
Key package caches by lockfile and environment/tool version as appropriate.
Test DB contents and browser storage should not leak between unrelated runs.
19. Performance regression testsβ
Phase 15 established performance budgets.
Testing can enforce stable signals such as:
client JS bytes
RSC/HTML payload size
query count
critical API p95 in controlled load test
image dimensions/asset size
Lighthouse range in controlled environment
Avoid noisy hard gates on uncontrolled internet/network timing.
20. Bundle budgetsβ
A CI job can compare route/client bundle output with a baseline.
Policy example:
unexpected +30 KB initial JS β fail/review
known intentional increase β update budget with explanation
Do not optimize only total repository package size; route delivery matters.
21. Query-count budgetsβ
For a critical list route:
expected <= 3 queries
can catch N+1 regressions more deterministically than a noisy latency threshold.
Use such assertions only where query count is a meaningful stable contract.
22. Accessibility regression in CIβ
Run automated browser scans on representative states.
Combine with:
semantic component assertions
keyboard E2E
manual review
A scanner-only gate is incomplete.
23. Test shard strategyβ
Large E2E suites can shard by file/project.
Keep tests independent so sharding does not change semantics.
If test B requires test A, redesign the fixture or explicitly group them as one scenario.
24. Quarantine policyβ
A quarantined test should have:
owner
reason
linked issue
last failure evidence
deadline/priority
Never create a permanent ignored folder that silently stops protecting a feature.
25. CI test matrix by riskβ
Example:
Every PR
unit/component
core integration
production build
Chromium critical E2E
Main
broader E2E
security regression
Nightly
cross-browser
load/performance
extended provider sandbox
Use repository size and deployment cadence to tune the matrix.
26. Release correlationβ
Attach:
commit SHA
build ID
test environment
browser version
schema version
where useful so failures can be reproduced.
Production checklistβ
- each test owns state
- DB fixtures support parallel runs
- time/randomness are controlled
- provider boundaries use layered doubles/sandboxes
- retry rate is monitored rather than ignored
- sleeps are replaced by conditions
- fork PRs cannot access protected secrets
- CI artifacts make failures diagnosable
- performance budgets use stable measurable signals
- quarantined tests have owners and deadlines
Interview questionsβ
Why can automatic retries be dangerous?β
Because they can turn a real race or shared-state bug into a green build. Use retries as evidence, monitor first-attempt failures, and repair the root cause.
Why is query count sometimes a better CI performance gate than latency?β
It can be deterministic and directly catch N+1 regressions, while wall-clock latency varies with CI load and infrastructure noise.
How do you test provider integrations without making CI unreliable?β
Use pure adapter mocks for domain tests, fake HTTP/contract fixtures for integration tests, and a smaller sandbox-backed suite for real provider confidence.