mcpField
C
condition-based-waiting

condition-based-waiting

github.com/bobmatnycTesting & quality78332 installsUpdated 15w ago
Repository

About condition-based-waiting

A testing skill that replaces guessed delays with waits for observable conditions. It helps developers reduce flaky tests caused by asynchronous operations, load, or parallel execution.

Key features

  1. 01Wait for conditions instead of fixed delays
  2. 02Handle events, state, counts, and files
  3. 03Build waits for compound conditions
  4. 04Use domain-specific event helpers

Use cases

  1. 01Replacing arbitrary sleep calls in tests
  2. 02Stabilizing tests that fail under load
  3. 03Waiting for asynchronous operations to finish
  4. 04Avoiding timeouts during parallel test runs

Install

Copy the command and run it in a terminal.

$npx skills add https://github.com/bobmatnyc/claude-mpm-skills --skill condition-based-waiting

After installing, type/condition-based-waitingin Claude Code to confirm it loaded.

Bundled filesmetadata.jsonreferences/patterns-and-implementation.md

Details

From the project README

Condition-Based Waiting

Overview

Flaky tests often guess at timing with arbitrary delays. This creates race conditions where tests pass on fast machines but fail under load or in CI.

Core principle: Wait for the actual condition you care about, not a guess about how long it takes.

When to Use

digraph when_to_use {
    "Test uses setTimeout/sleep?" [shape=diamond];
    "Testing timing behavior?" [shape=diamond];
    "Document WHY timeout needed" [shape=box];
    "Use condition-based waiting" [shape=box];

    "Test uses setTimeout/sleep?" -> "Testing timing behavior?" [label="yes"];
    "Testing timing behavior?" -> "Document WHY timeout needed" [label="yes"];
    "Testing timing behavior?" -> "Use condition-based waiting" [label="no"];
}

Use when:

  • Tests have arbitrary delays (setTimeout, sleep, time.sleep())
  • Tests are flaky (pass sometimes, fail under load)
  • Tests timeout when run in parallel
  • Waiting for async operations to complete

Don't use when:

  • Testing actual timing behavior (debounce, throttle intervals)
  • Always document WHY if using arbitrary timeout

Core Pattern

// ❌ BEFORE: Guessing at timing
await new Promise(r => setTimeout(r, 50));
const result = getResult();
expect(result).toBeDefined();

// ✅ AFTER: Waiting for condition
await waitFor(() => getResult() !== undefined);
const result = getResult();
expect(result).toBeDefined();

Quick Patterns

ScenarioPattern
Wait for eventwaitFor(() => events.find(e => e.type === 'DONE'))
Wait for statewaitFor(() => machine.state === 'ready')
Wait for countwaitFor(() => items.length >= 5)
Wait for filewaitFor(() => fs.existsSync(path))
Complex conditionwaitFor(() => obj.ready && obj.value > 10)

Implementation

Generic polling function:

async function waitFor<T>(
  condition: () => T | undefined | null | false,
  description: string,
  timeoutMs = 5000
): Promise<T> {
  const startTime = Date.now();

  while (true) {
    const result = condition();
    if (result) return result;

    if (Date.now() - startTime > timeoutMs) {
      throw new Error(`Timeout waiting for ${description} after ${timeoutMs}ms`);
    }

    await new Promise(r => setTimeout(r, 10)); // Poll every 10ms
  }
}

See @example.ts for complete implementation with domain-specific helpers (waitForEvent, waitForEventCount, waitForEventMatch).

For detailed patterns, implementation guide, and common mistakes, see @references/patterns-and-implementation.md

Real-World Impact

From debugging session (2025-10-03):

  • Fixed 15 flaky tests across 3 files
  • Pass rate: 60% → 100%
  • Execution time: 40% faster
  • No more race conditions

Comments

Markdown supported