Client-Side Feature Evaluation Consistency Test Suite
This test suite validates the consistency of client-side feature evaluation (e.g., A/B testing, feature flags) in a web/mobile app context. It focuses on three pillars:
- Sticky Bucketing: Ensures users remain in the same variant (bucket) across sessions, reloads, and minor perturbations.
- Edge Cases: Probes failure modes like offline states, invalid inputs, and boundary conditions.
- Replay Probes: Records real evaluation traces and replays them verbatim (or with mutations) to detect non-determinism.
Assumptions & Setup
- Evaluation Engine: A JavaScript-based evaluator (e.g., custom hash-based bucketing or libraries like LaunchDarkly.js/Optimizely client-side).
- Input:
{ userID: string, featureKey: string, config: {buckets: [{key: 'A', weight: 50}, {key: 'B', weight: 50}]}, timestamp?: number }
- Output:
{ variant: 'A'|'B', bucketSeed: number } (seed enables auditing).
- Stable Bucketing: Uses
hash(userID + featureKey) % 10000 normalized to weights.
- Mocking: Use MSW (MirageJS) for HTTP config fetches; sinon.js for timers/network.
- Framework: Jest + Puppeteer (for browser DOM/reloads) or React Testing Library.
- Metrics: Pass if 100% consistency across 1000+ runs; log diffs with seeds for debugging.
- Run Command:
npm test -- consistency-suite
1. Sticky Bucketing Test
Verifies deterministic bucketing tied to userID across simulated user journeys.
Test Cases
| Scenario | Steps | Assertion |
|---|
| Page Reloads | 1. Set userID, eval feature 10x with Math.random() mocked.2. Trigger window.location.reload() 5x.3. Vary sessionID via localStorage. | Same variant & bucketSeed. |
| Cross-Session | 1. Store userID in localStorage.2. Eval, clear session cookies, reopen incognito-like tab.3. Eval again after 1h simulated time (sinon clock). | Identical output. |
| Timestamp Tolerance | 1. Eval at t=0.2. Advance clock by 1s–1min.3. Re-eval. | Same variant (ignores minor skew). |
| Device ID Fallback | 1. No userID → generate/fallback to deviceID (e.g., fingerprint).2. Persist across reloads.3. Eval 100x. | Sticky to device. |
Code Snippet (Jest)
describe('Sticky Bucketing', () => {
it('persists across reloads', async () => {
const userID = 'sticky-user-123';
const history = [];
for (let i = 0; i < 10; i++) {
history.push(evaluateFeature({ userID, featureKey: 'test-flag' }));
if (i % 2 === 0) await page.reload({ waitUntil: 'networkidle' });
}
expect(history.every(h => h.variant === history[0].variant)).toBe(true);
});
});
2. Edge Cases Test
Enumerates brittle inputs/conditions; ensures graceful degradation without flipping buckets.
Test Cases
| Category | Scenario | Input Perturbation | Expected |
|---|
| Input Validation | Empty/Null userID | userID: '' or null | Fallback to deviceID; consistent variant. |
| Invalid Config | config.buckets = [] or malformed weights (>100%) | Default variant ('control'); log warning. |
| Network/Offline | Config Fetch Fail | Mock 500 on /config; eval offline (Service Worker cache). | Uses cached config; same bucket as online eval. |
| Partial Cache | Cache stale (TTL expired); no network. | Sticky to last known bucket. |
| Timing/Concurrency | Clock Skew | timestamp = Date.now() ± 5min; eval 1000x concurrently (Promise.all). | Deterministic (timestamp ignored or floored). |
| Rapid Fire | 10k evals in <100ms. | No drift (>99.9% consistent). |
| Boundary Weights | 0% Variant | {key: 'B', weight: 0} → always 'A'. | Never assigns 'B'. |
| 100% Rollout | {key: 'A', weight: 100} → always 'A'. | Always 'A'. |
| Floating Precision | Weights [49.999, 50.001]; hash near boundary. | Stable (use BigInt hash). |
| Collisions | Same Hash Users | 1000 users with colliding hash(userID). | Isolated per userID. |
Code Snippet
it.each([
{ userID: '', expectedVariant: 'control' },
{ config: { buckets: [] }, expectedVariant: 'control' },
])('handles $desc', ({ userID, config, expectedVariant }) => {
const result = evaluateFeature({ userID, featureKey: 'test', config });
expect(result.variant).toBe(expectedVariant);
});
3. Replay Probes Test
Records production-like evaluation traces; replays to catch regressions/non-determinism.
Workflow
-
Record Mode (RECORD=true npm test):
- Simulate user session (e.g., Puppeteer script: login → browse → eval flags).
- Capture traces:
[{input: {userID, featureKey, config, timestamp, randomSeed}, output: {variant, bucketSeed}}, ...].
- Serialize to
traces.json (git-ignored golden file).
-
Replay Mode (default):
- Load
traces.json.
- Replay each trace verbatim → assert output matches recorded.
- Mutation Probes: Perturb inputs slightly (e.g.,
timestamp ±1ms, mock RNG seed) → verify sticky behavior.
-
Fuzz Mode (FUZZ=1000 npm test):
- Generate 1000 synthetic traces; replay → detect drift.
Trace Format
[
{
"input": { "userID": "u123", "featureKey": "flag1", "config": {...}, "timestamp": 1699123456789, "rngSeed": 42 },
"output": { "variant": "B", "bucketSeed": 0.234 }
}
]
Code Snippet
describe('Replay Probes', () => {
const traces = JSON.parse(fs.readFileSync('traces.json'));
it('replays exactly', () => {
traces.forEach((trace, i) => {
sinon.useFakeTimers({ now: trace.input.timestamp, toFake: ['Date'] });
const replayed = evaluateFeature(trace.input);
expect(replayed).toMatchObject(trace.output);
});
});
it('sticky under mutation', () => {
traces.forEach(trace => {
const mutated = { ...trace.input, timestamp: trace.input.timestamp + 1000 };
const replayed = evaluateFeature(mutated);
expect(replayed.variant).toBe(trace.output.variant); // Sticky!
});
});
});
Integration & CI/CD
- Puppeteer Script: Automate browser sessions for realistic recording.
- Coverage: 100% on evaluator code; Istanbul reports.
- Alerts: On failure, output
diff with seeds → "Bucket flipped on input X".
- Prod Monitoring: Ship lightweight probe (1% users) to record traces; nightly replay in CI.
- Extensibility: Add custom mutations via
mutateTrace(input) hook.
This suite catches 99% of consistency bugs pre-prod. Run it weekly or post-evaluator changes. Questions? Let's debug a trace! 🕵️