Skip to main content

Published

Feature flag coverage reference

In brief: Environment variables, the x-testchimp-flags header contract (format, 4096-byte cap, truncation header) with a Python implementation, the three MCP and CLI tools, and which providers, SDKs, backend languages and test runners are supported.

Environment variables​

VariableWhereDefaultEffect
TESTCHIMP_FLAG_ECHOBackend under testunset1 or true turns on @testchimp/flags/server: it collects evaluations per request and adds the x-testchimp-flags header. Set it in test environments only, never in production.
TESTCHIMP_DISABLE_FLAG_CAPTURETest runnerunset1 turns flag capture off in @testchimp/playwright: no window.__TESTCHIMP_FLAGS__, no header reading, no upload.
TESTCHIMP_FLAG_CAPTURE_DRAIN_TIMEOUT_MSTest runner2000How long the fixture waits at test end for pages to hand over buffered evaluations. Accepts 100 to 10000.

Flag capture is on by default on the test side. It is independent of TESTCHIMP_ENABLE_API_CAPTURE.

Header contract​

The header is the interface between your backend and TestChimp. Any language can implement it.

x-testchimp-flags: v1.<base64url(JSON array of {k, v, p})>
x-testchimp-flags-truncated: 1 (only when entries were dropped)
  • k is the flag key, v is the arm as a string, and p is the provider id: openfeature, launchdarkly, posthog, statsig or unknown.
  • Entries are deduplicated by (k, v).
  • base64url has no padding.
  • The encoded value must stay within 4096 bytes. Keep the first entries that fit, and set x-testchimp-flags-truncated: 1 if any were dropped.
  • Set the header only when at least one entry was recorded, and only when the echo is enabled.
  • No request header is needed, and no CORS change: the fixture reads response headers through Playwright and attributes each response to the test that made the request.

Implement it in another language​

A Python implementation, about 25 lines:

import base64, json

MAX_BYTES = 4096

def encode(entries):
return "v1." + base64.urlsafe_b64encode(json.dumps(entries, separators=(",", ":")).encode()).rstrip(b"=").decode()

def flag_headers(arms):
"""arms: (flag_key, variant, provider_id) tuples observed while handling one request."""
seen, kept, truncated = set(), [], False
for k, v, p in arms:
if (k, v) in seen:
continue
seen.add((k, v))
if len(encode(kept + [{"k": k, "v": v, "p": p}]).encode()) > MAX_BYTES:
truncated = True
break
kept.append({"k": k, "v": v, "p": p})
if not kept:
return {}
headers = {"x-testchimp-flags": encode(kept)}
if truncated:
headers["x-testchimp-flags-truncated"] = "1"
return headers

Call flag_headers from your framework's response hook, and only when the echo is enabled. Collect the arms per request, for example from your flag SDK's evaluation hook, so concurrent requests never share entries.

Package API​

@testchimp/flags/web​

ExportUse
createOpenFeatureHook()OpenFeature web SDK hook. Reports the variant, or the value when there is no variant.
instrumentLaunchDarkly(options)Wraps LaunchDarkly JS initialize options with a flag-used inspector. Pass the result to initialize.
instrumentPostHog(posthog)Reads PostHog JS $feature_flag_called events. Call once after posthog.init.
reportFlag(flagKey, variant, providerId)Report an arm yourself, for any other SDK.

All of them do nothing when window.__TESTCHIMP_FLAGS__ is absent.

@testchimp/flags/server​

ExportUse
flagCollectionMiddleware()Express and Connect middleware.
fastifyFlagCollectionFastify plugin.
withFlagCollection(handler)Wrapper for Next.js App Router route handlers and any (req, res) handler.
createOpenFeatureServerHook()OpenFeature server SDK hook.
instrumentLaunchDarklyNode(ldClient)@launchdarkly/node-server-sdk v9.3 or later, after init.
instrumentPostHogNode(client)posthog-node: getFeatureFlag, isFeatureEnabled, evaluateFlags. isFeatureEnabled on a multivariate flag names no variant, so it counts no arm.
reportFlag(flagKey, variant, providerId)Report an arm yourself.

Each request gets its own collector through AsyncLocalStorage. All of them do nothing unless TESTCHIMP_FLAG_ECHO is set.

@testchimp/playwright​

import { testchimp } from '@testchimp/playwright';

testchimp.flags.force('new-checkout', true, 'launchdarkly');
testchimp.flags.force('pricing-page-variant', 'annual-first');

testchimp.flags.force(flagKey, variant, providerId?) records the arm as forced for the current test. variant can be a string, boolean or number. Use it when the test pins the value without mocking a provider endpoint, for example with a query parameter or cookie. Outside the fixture it does nothing.

The fixture also records forced values when a test mocks these provider endpoints with route.fulfill:

ProviderEndpoint
LaunchDarkly/sdk/eval/ and /sdk/evalx/ on launchdarkly.com hosts
PostHog/decide and /flags
Statsig/v1/initialize, when the request asks for unhashed names ("hash": "none")

MCP and CLI tools​

The same tools are available over MCP, the testchimp CLI and POST /api/mcp/* with a project API key. See the programmatic guide for example calls.

get-feature-flag-setup-status​

Read-only. Takes no arguments. Use it to drive setup and to confirm it worked. It never returns credentials.

FieldMeaning
providerConnected, providerIdWhether a flag provider is connected, and which one
lastSyncAtMillis, lastSyncStatusLast catalog sync time and result (FF_SYNC_OK or FF_SYNC_FAILED)
catalogFlagCountFlags in the synced catalog
anyEvaluationsIngested, lastEvaluationAtMillisWhether any test run has reported flags, and when the last one did
sourcesSeenSources seen so far: FRONTEND, BACKEND, FORCED
observedFlagKeysFlag keys seen in test runs (capped)
observedUnmappedFlagKeysFlag keys seen in tests linked to no story (capped at 50)
settingsUrl, coverageUrlLinks to the provider settings and the coverage page

get-feature-flag-coverage​

Read-only. Returns stories with their relevant flags and arms.

InputCLI flagMeaning
storyOrdinalIds--story-ordinal-idsLimit to these stories
scopes--folder-path, --artifact-type, --scopesPlans folders or files to include
branchName--branch-nameBranch to read executions from. An unknown branch returns an error.
environment--environmentExecution environment
windowStartMillis, windowEndMillis--window-start-millis, --window-end-millisTime window. Default: the last 30 days.
release--releaseUse the release's scope and executions
untestedOnly--all-arms turns it offDefault true: only stories and arms with gaps
maxStories--max-storiesDefault 20, maximum 100

Pass the whole request as JSON with --json-input.

Each story in stories has storyId, storyOrdinalId, storyTitle, armsCovered, armsTotal, untestedArmCount, linkedScenarios, and flags. Each flag has flagKey, displayName, kind, relevance (AUTO, PINNED or EXCLUDED), catalogKnown, archived and arms. Each arm has:

  • variantKey and displayName;
  • status: ARM_TESTED, ARM_TESTED_FORCED, ARM_UNTESTED or ARM_IGNORED;
  • inCatalog and rolloutPercent;
  • sources, the sources that recorded it;
  • coveringTests, each with testId, testName and latestFailed.

The response also has matchingStoryCount, truncated, flagsRelevant, armsCovered, armsTotal, providerConnected, anyEvaluationsIngested, observedUnmappedFlagKeys and coverageUrl.

set-story-feature-flag-relevance​

Mutating and idempotent. Pins a flag to a story, excludes it, or resets it to automatic.

InputCLI flagMeaning
storyOrdinalId or storyId--story-ordinal-id, --story-idThe story
flagKey--flag-keyThe flag
state--stateAUTO, PINNED or EXCLUDED

Returns the stored state.

Support matrix​

AreaSupportedNot yet
Catalog sync (providers)LaunchDarkly, PostHog, StatsigUnleash, GrowthBook, Flagsmith, ConfigCat
Frontend captureOpenFeature web SDK (any provider), LaunchDarkly JS, PostHog JS, reportFlagStatsig SDK hooks
Backend captureNode: Express, Connect, Fastify, Next.js route handlers, any (req, res) handler; OpenFeature server SDK, LaunchDarkly Node, PostHog NodeJava, Python and Go hooks (use the header contract)
Backend scopeThe service that answers the test's requestServices behind it, queue consumers, cron jobs, background workers
Test runnersPlaywright with @testchimp/playwright, including the request fixtureMobile test runners
Coverage modelEach flag's arms on their ownCombinations of flags

Flags from an OpenFeature provider that TestChimp cannot sync are still captured, and show as Catalog unknown.

FAQ

What is the x-testchimp-flags header?

A response header your backend adds in test environments: v1. followed by base64url JSON of {k, v, p} entries, capped at 4096 bytes.

What happens when the header is too long?

The first entries that fit are kept and x-testchimp-flags-truncated: 1 is set.

Can a non-Node backend report flags?

Yes, by implementing the header contract. The reference includes a Python implementation of about 25 lines.