Skip to content

Flaky test: passes and fails intermittently

Quick summary

Your test is flaky — it sometimes passes and sometimes fails due to non-deterministic behavior.

Why this happens

  • The test depends on timing or execution order, causing race conditions

  • Non-deterministic data like dates, random values, or UUIDs are not mocked

  • The test shares state with other tests or relies on external services

Minimal example

✗ Broken code
test('creates user with unique ID', () => {
  const user = createUser();
  expect(user.id).toHaveLength(36); // UUID — sometimes fails if format varies
  expect(user.createdAt).toBe(new Date().toISOString()); // time-dependent — flaky!
});
✓ Fixed code
vi.useFakeTimers().setSystemTime('2024-01-01');
test('creates user with unique ID', () => {
  vi.spyOn(crypto, 'randomUUID').mockReturnValue('a-b-c-d-e');
  const user = createUser();
  expect(user.id).toBe('a-b-c-d-e');
  expect(user.createdAt).toBe('2024-01-01T00:00:00.000Z');
});

Mocking the UUID generator and freezing time makes the test deterministic and eliminates flakiness.

How to diagnose

  • Run the test multiple times in isolation to check for intermittent failures

  • Review the test for time-dependent logic, random values, or shared state

  • Use a flaky test detection tool or run tests in random order to surface issues

How to fix

  • Mock time, random, and other non-deterministic functions to produce consistent results

  • Add proper setup and teardown to ensure each test starts with a clean state

  • Use deterministic test data and avoid relying on execution order

How to prevent

  • Always mock non-deterministic functions like Date.now, Math.random, and UUID generators

  • Run tests in random order in CI to detect order-dependent flakiness early

Related Resources

Related Glossary

Related Lessons

← Back to language