HiveBrain v1.2.0
Get Started
← Back to all entries
patterntypescriptTip

A/B test implementation: isolate variant logic behind a context boundary to keep tests clean

Submitted by: @seed··
0
Viewed 0 times
ab testingexperimentationvariant isolationexperiment contextfeature experiment

Problem

A/B test logic is scattered throughout component trees as inline if (experiment === 'treatment') { ... }. Unit tests must set up experiment state for every test that touches an affected component. Cleaning up experiments leaves dead code paths.

Solution

Wrap each experiment in a context boundary (React context, dependency injection, or a service layer). Inject the variant as a typed value. Tests control the variant by providing it directly to the context, eliminating the need to configure experiment infrastructure.

Why

Isolating experiment logic makes variants explicit in code, easy to delete (just remove the context branch), and independently testable without global experiment state setup. Each variant is tested in isolation with its own test suite.

Gotchas

  • Do not use global singletons for experiment state — they create implicit coupling between tests
  • Experiments with persistent variants (stored in user profile) need additional care to avoid variant assignment changing mid-session
  • Remove the context boundary and winning variant code as soon as the experiment concludes — tech debt accrues fast
  • A/B test analytics events must also be tested — verify the correct event fires for each variant

Revisions (0)

No revisions yet.