Integration Tests Fail Randomly Due to Shared State
Your integration tests pass when run individually but fail randomly when run as a suite. The failures are non-deterministic: different tests fail on different runs, tests that were passing start failing after adding new tests, and the CI pipeline has become unreliable with intermittent failures.
Flaky tests are a serious productivity drain. Developers lose trust in the test suite, start ignoring failures ('it's just a flaky test'), and eventually stop running tests altogether. Real bugs hide behind the noise of flaky failures.
Claude Code generates integration tests that work in isolation but share database state, use hardcoded ports, rely on test ordering, or have timing dependencies that cause failures when tests run in parallel or in different orders.
Error Messages You Might See
Common Causes
- Shared database state between tests — One test creates data that another test doesn't expect, or a test deletes data another test needs
- No database cleanup between tests — Tests don't reset the database to a known state before or after running
- Hardcoded ports — Multiple test files try to start servers on the same port, causing EADDRINUSE errors
- Test order dependency — Tests rely on being run in a specific order because earlier tests set up state that later tests need
- Timing-dependent assertions — Tests use setTimeout or fixed delays that are long enough locally but too short in CI
How to Fix It
- Use database transactions for isolation — Wrap each test in a transaction that rolls back after the test completes, ensuring clean state
- Create fresh state in each test — Use beforeEach to set up exactly the data each test needs. Never rely on state from other tests
- Use random ports — Start test servers on port 0 (OS assigns a random available port) to avoid conflicts
- Randomize test order — Configure your test runner to randomize test execution order to expose hidden dependencies
- Replace timeouts with polling — Instead of await sleep(1000), poll for the expected condition with a timeout: await waitFor(() => expect(result).toBe(expected))
- Use testcontainers — Spin up isolated database instances per test suite using Docker containers
Real developers can help you.
You don't need to be technical. Just describe what's wrong and a verified developer will handle the rest.
Get HelpFrequently Asked Questions
How do I isolate database state between integration tests?
The best approach is to wrap each test in a database transaction and roll it back after the test. Alternatively, use TRUNCATE on all tables in beforeEach, or use testcontainers to spin up a fresh database per test suite.
Why do my tests pass locally but fail in CI?
CI environments are typically slower and have less CPU. Timing-dependent tests that pass locally may timeout in CI. Replace fixed delays with polling/waitFor patterns and increase timeouts for CI environments.