@testchimp/flags
v0.1.1
Published
Feature flag evaluation hooks for apps under test. Reports which flag arms a TestChimp test ran, from the browser and from the backend.
Readme
@testchimp/flags
Feature flag hooks for apps under test. They tell TestChimp which flag arms your tests actually ran, so the coverage view can show untested arms.
- Web (
@testchimp/flags/web): reports flags the browser evaluates, through OpenFeature, the LaunchDarkly JS SDK or PostHog JS. - Server (
@testchimp/flags/server): echoes the flags a backend evaluated for a request back to the test, in a response header. It works with Express, Connect, Fastify, Next.js route handlers, and any(req, res)handler, and includes hooks for OpenFeature, LaunchDarkly Node and PostHog Node.
No runtime dependencies. OpenFeature, LaunchDarkly and PostHog are not imported, so the hooks work with any version that has the callbacks described below.
npm install @testchimp/flagsSafety: nothing happens outside a test
This is the most important property, and it is tested.
- Web: every function checks for
globalThis.__TESTCHIMP_FLAGS__. The TestChimp Playwright fixture defines that global, and only in tests. In production there is no global, so the hooks install no wrappers, make no network calls, and throw nothing. - Server: nothing happens unless
TESTCHIMP_FLAG_ECHO=1(ortrue) is set. Set it only in test environments. When it is unset, no header is added and no per-request state is kept.
Web
Report evaluations through the SDK you already use:
import { createOpenFeatureHook, instrumentLaunchDarkly, instrumentPostHog, reportFlag } from '@testchimp/flags/web';
// OpenFeature web SDK
OpenFeature.addHooks(createOpenFeatureHook());
// LaunchDarkly JS SDK: inspectors can only be set at initialize time
const client = LDClient.initialize(clientSideId, context, instrumentLaunchDarkly({ bootstrap }));
// PostHog JS: call once after init
posthog.init(projectKey, options);
instrumentPostHog(posthog);
// Anything else: report the arm yourself
reportFlag('checkout-layout', 'compact', 'my-provider');Each provider's evaluations reach the fixture with the right provider id: openfeature, launchdarkly or posthog.
| Provider | Hook | How it captures |
|---|---|---|
| OpenFeature (web) | createOpenFeatureHook() | The hook's after stage. Reports the variant, or the value when there is no variant. |
| LaunchDarkly JS | instrumentLaunchDarkly(options) | A flag-used inspector, which the SDK calls on each variation call. allFlags() is not counted. |
| PostHog JS | instrumentPostHog(posthog) | Wraps posthog.capture and reads the $feature_flag_called event that getFeatureFlag emits. Lookups made with send_event: false emit no event, so they are not captured. |
instrumentLaunchDarkly returns a new options object, so pass its result into initialize. It returns the options unchanged outside a test.
Server
Set TESTCHIMP_FLAG_ECHO=1 in the test environment that runs the backend. Then add the middleware (or wrapper) that matches your framework.
// Express or Connect
import { flagCollectionMiddleware } from '@testchimp/flags/server';
app.use(flagCollectionMiddleware());
// Fastify
import { fastifyFlagCollection } from '@testchimp/flags/server';
await app.register(fastifyFlagCollection);
// Next.js App Router route handler, or any (req, res) handler
import { withFlagCollection } from '@testchimp/flags/server';
export const GET = withFlagCollection(async (request: Request) => Response.json(await loadOrders()));Then wire the provider hook once, at startup:
import { createOpenFeatureServerHook, instrumentLaunchDarklyNode, instrumentPostHogNode } from '@testchimp/flags/server';
OpenFeature.addHooks(createOpenFeatureServerHook()); // OpenFeature server SDK
instrumentLaunchDarklyNode(ldClient); // @launchdarkly/node-server-sdk v9.3+, after init
instrumentPostHogNode(posthogClient); // posthog-node: getFeatureFlag, isFeatureEnabled, evaluateFlagsreportFlag(flagKey, variant, providerId) is also exported, for providers without a hook.
isFeatureEnabled on a multivariate PostHog flag answers true without naming the variant, so TestChimp can't tell which arm ran and doesn't count it. Use getFeatureFlag, or evaluateFlags (its isEnabled reports the served variant).
Each request gets its own collector, through AsyncLocalStorage. Concurrent requests never see each other's flags.
Backend-only flags need the echo
A flag evaluated only in the backend shows as untested unless TESTCHIMP_FLAG_ECHO=1 is set on the backend. Flags evaluated in the browser need no backend setup, because the fixture captures them directly.
Only the service that answers the browser's request echoes its flags. Deeper services, queue consumers, cron jobs and background workers are out of scope for v1.
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)kis the flag key,vis the arm as a string,pis the provider id (openfeature,launchdarkly,posthog,statsig, orunknown).- 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: 1if any were dropped. - Set the header only when at least one entry was recorded. Set it only when the echo is enabled.
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 headersCall flag_headers from your framework's response hook, and only when the echo is enabled. The Playwright fixture reads the header from every response, so no CORS change is needed in the app under test.
Verified against
@launchdarkly/node-server-sdk9.17.1: theafterEvaluationhook fires from a realvariationcall.@openfeature/server-sdk1.23.0: theafterhook fires from a realgetBooleanValueandgetStringValuecall.- The header decodes with the
@testchimp/playwrightfixture decoder. - The web entry is checked to contain no Node-only module, and makes no network calls (unit tests).
- The LaunchDarkly JS inspector, PostHog
$feature_flag_calledandposthog-nodemethod shapes are taken from the providers' current documentation. They are covered by unit tests, but not yet by a live browser run.
Not in v1
- Statsig adapters. Statsig gates reach TestChimp through the fixture's bootstrap capture only.
- Java, Python and Go server hooks. Use the header contract above.
- Flags evaluated outside the service that answers the browser's request.
License
MIT
