How to test flag-gated React code with Vitest

Test flag-gated behavior with the actual Experiment client, deterministic variants and controlled fetches. Then check existing remote assignments separately in a React fixture.

  • React
  • Vite
  • Unified SDK 1.2.1
  • 20 min

Chris Tam · Last updated 13 November 2026

Feature flags need predictable application behavior when a flag is missing or a refresh fails. I'll build a React report fixture with a standard view and an expanded view. Vitest controls the real SDK's documented inputs; it doesn't replace variant() with a mocked answer.

The local tests need no project key or network. An optional browser check uses your existing designated test flag and users to verify remote assignment separately. The fixed report counts are demo data, not a query of real reports.

What you'll build

A standalone React app and Vitest suite using the Unified SDK's actual Experiment client. Tests cover expanded, control, unknown and missing variants; real-client cache behavior on fetch failure; explicit clearing before another identity; and blank-key fallback.

Prerequisites

  • Node.js 22.12 or later and Corepack for pnpm.
  • An Amplitude test project and its ingestion API key. Open Organization settings > API Keys and select the test project.
  • The project data center, US or EU. Preserve your existing consent flow when adapting the example.

No Amplitude account yet? A free account is enough for this tutorial; nothing here needs a paid plan. Sign up for free to get your project API key.

1. Create the standalone app

I'll use the Browser Unified SDK package installation in a small Vite app. The versions below are pinned to the tested example.

Terminal
mkdir react-feature-flags-vitest
cd react-feature-flags-vitest
mkdir -p src tests
corepack enable
package.json
{
  "name": "amplitude-react-feature-flags-vitest",
  "version": "1.0.0",
  "private": true,
  "type": "module",
  "packageManager": "pnpm@10.33.2+sha512.a90faf6feeab71ad6c6e57f94e0fe1a12f5dcc22cd754db40ae9593eb6a3e0b6b12e3540218bb37ae083404b1f2ce6db2a4121e979829b4aff94b99f49da1cf8",
  "engines": {
    "node": ">=22.12.0",
    "pnpm": ">=10.21.0"
  },
  "scripts": {
    "dev": "vite --host 127.0.0.1",
    "build": "vite build",
    "preview": "vite preview --host 127.0.0.1",
    "test": "vitest run"
  },
  "dependencies": {
    "@amplitude/unified": "1.2.1",
    "react": "19.3.1",
    "react-dom": "19.3.1"
  },
  "devDependencies": {
    "vite": "8.3.6",
    "vitest": "5.0.5",
    "jsdom": "31.0.0"
  }
}
pnpm-workspace.yaml
minimumReleaseAge: 10080
trustPolicy: no-downgrade
.gitignore
node_modules/
dist/
.env
.env.local
.env.*.local
index.html
<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Form drop-off demo</title>
  </head>
  <body>
    <div id="root"></div>
    <script type="module" src="/src/main.jsx"></script>
  </body>
</html>
.env.example
VITE_AMPLITUDE_API_KEY=
VITE_AMPLITUDE_DEPLOYMENT_KEY=
VITE_AMPLITUDE_SERVER_ZONE=US
Terminal
corepack prepare pnpm@10.33.2 --activate
pnpm install
cp .env.example .env.local

Put the test-project key in VITE_AMPLITUDE_API_KEY in .env.local, and set VITE_AMPLITUDE_SERVER_ZONE to US or EU. Vite exposes VITE_ variables in the browser bundle. The project API key is public and has the minimum scope needed to ingest data; a server secret key stays out of browser code.

In an existing application, merge the changes into its current Amplitude module and application flow. Keep authentication, consent, routes, and other instrumentation. Don't add another SDK installation or replace production files with the demo.

2. Initialize the actual client for controlled tests

I'll use documented Experiment options to supply initial variants or a controlled HTTP client. Each test gets a separate Unified instance and instance name. The application function maps only expanded to the expanded view; unknown values use control.

vitest.config.js
import { defineConfig } from 'vitest/config';
export default defineConfig({ test: { environment: 'jsdom', restoreMocks: true } });
src/flags.js
import { createInstance } from '@amplitude/unified';
export const flagKey='report-layout';
export function reportView(variant) { return variant?.value==='expanded'?'expanded':'control'; }
export async function createReportClient({apiKey,deploymentKey,zone='US',instanceName='build-vitest-demo',experimentOptions={}}) {
  if(!apiKey?.trim()||!deploymentKey?.trim())return null;
  const analytics=createInstance();
  await analytics.initAll(apiKey,{instanceName,serverZone:zone==='EU'?'EU':'US',analytics:{autocapture:false,remoteConfig:{fetchRemoteConfig:false}},sessionReplay:{sampleRate:0},engagement:{skip:true},experiment:{deploymentKey,fetchOnStart:false,pollOnStart:false,automaticFetchOnAmplitudeIdentityChange:false,automaticExposureTracking:false,retryFetchOnFailure:false,fetchTimeoutMillis:1000,...experimentOptions}});
  const experiment=analytics.experiment();
  if(!experiment)throw Error('Experiment did not initialize.');
  return {analytics,experiment};
}
export async function loadReport(client,user,{clear=false}={}) {
  if(!client)return {view:'control',assigned:false};
  if(clear)client.experiment.clear();
  await client.experiment.fetch(user);
  const variant=client.experiment.all()[flagKey];
  return {view:reportView(variant),assigned:typeof variant?.value==='string',value:variant?.value??null};
}

The tests run in jsdom and use Vitest's request spy, while the SDK's initialization, fetch, variant, cache and clear logic remain real. No initial variants or controlled HTTP responses establish a real remote assignment.

A failed fetch can resolve with existing cached variants. loadReport intentionally demonstrates that SDK behavior. It doesn't label a resolved fetch as fresh remote success. The browser identity-switch path clears the cache before fetching so a prior user's expanded assignment isn't reused after a failed new-user fetch.

Why. A unit test that mocks variant() checks the branch you told it to return. Controlling the real client's inputs also exercises fallback and cache behavior that can change the application's result.

3. Keep remote assignment and exposure separate

I'll initialize once for the browser, pass both ingestion and client deployment keys, then change identity only inside an explicit test-user action. Automatic exposure is disabled; the UI exposes the assignment after rendering the corresponding report.

src/analytics.js
import { createReportClient, loadReport, flagKey } from './flags.js';
let ready;
export function initializeAnalytics(){
 if(!ready)ready=createReportClient({apiKey:import.meta.env.VITE_AMPLITUDE_API_KEY,deploymentKey:import.meta.env.VITE_AMPLITUDE_DEPLOYMENT_KEY,zone:import.meta.env.VITE_AMPLITUDE_SERVER_ZONE});
 return ready.then(client=>({status:client?'ready':'disabled',client})).catch(()=>({status:'error',client:null}));
}
export async function chooseReport(client,userId){
 if(!client)return {view:'control',assigned:false};
 client.analytics.setUserId(userId);
 return loadReport(client,{user_id:userId,device_id:client.analytics.getDeviceId()},{clear:true});
}
export function exposeReport(client){client?.experiment.exposure(flagKey);}

Use the existing flag's exact key and your own designated test identities when adapting the fixture. The included identities belong to the author's test project. No button changes targeting or deployment. A blank key gives application control without initializing the client.

Unified1.2.1 includes beta Experiment plugin1.0.0-beta.52. The versions are pinned and tested here; assess that dependency before adopting. Analytics autocapture is off, replay0 and guides and surveys skipped. Remote analytics fetching is disabled so local collection choices apply.

MCP. Your coding agent can read the current SDK's initialization, cache and exposure rules with the Docs MCP server. It doesn't supply a real project assignment to a unit test.

4. Render the assigned view before exposing it

I'll keep a small report fixture in React and select between standard and expanded views. The effect exposes once per completed load token after React commits that view; re-renders under Strict Mode don't create a second exposure for that token.

src/App.jsx
import React,{useRef,useState,useEffect} from 'react';
import {chooseReport,exposeReport} from './analytics.js';
export function App({analytics}){
 const [result,setResult]=useState({view:'control',assigned:false}),[busy,setBusy]=useState(false),[token,setToken]=useState(0),[message,setMessage]=useState('Choose an existing designated test identity.');const exposed=useRef(-1);
 useEffect(()=>{if(result.assigned&&exposed.current!==token){exposed.current=token;exposeReport(analytics.client);}},[result,token,analytics.client]);
 async function load(user){if(busy)return;setBusy(true);try{const next=await chooseReport(analytics.client,user);setResult(next);setToken(x=>x+1);setMessage(next.assigned?'Assignment loaded; inspect the result.':'No assignment; safe control.');}catch{setResult({view:'control',assigned:false});setMessage('Fetch failed; safe control.');}finally{setBusy(false);}}
 return <main><h1>Test a flag-gated report</h1><p>The report is a local fixture. These controls use existing test identities; they don't change targeting.</p>
 <button id="control" disabled={busy} onClick={()=>load('build-ios-flags-control-20261029')}>Load control test user</button>
 <button id="expanded" disabled={busy} onClick={()=>load('build-web-flags-demo')}>Load expanded test user</button>
 <p role="status">{message}</p><p>Analytics: <strong>{analytics.status}</strong></p><section id="report" data-view={result.view}><h2>{result.view==='expanded'?'Expanded report':'Standard report'}</h2><p>Saved reports:3</p>{result.view==='expanded'&&<p id="extra-detail">Weekly comparison: +2 reports</p>}</section></main>;
}
src/style.css
:root { font-family: Helvetica, Arial, sans-serif; color: #000000; background: #F2F4F8; }
body { margin: 0; }
main { max-width: 760px; margin: 40px auto; padding: 32px; background: #FFFFFF; border-radius: 16px; }
h1 { font-size: 36px; }
p { line-height: 1.5; }
.eyebrow { font-size: 12px; letter-spacing: 0.08em; }
nav { display: flex; gap: 20px; flex-wrap: wrap; padding: 16px 0; }
a { color: #0052F2; }
section, aside { border-top: 1px solid #D5D9E0; margin-top: 24px; padding-top: 24px; }
label { display: block; margin-bottom: 8px; }
button, select, [role='button'] { font: inherit; padding: 10px 14px; margin: 0 12px 12px 0; border: 1px solid #000000; border-radius: 6px; color: #000000; background: #FFFFFF; }
button, [role='button'] { cursor: pointer; }
#save-settings { color: #FFFFFF; background: #0052F2; border-color: #0052F2; }
[role='button'] { display: inline-block; }
:focus-visible { outline: 3px solid #0052F2; outline-offset: 3px; }
code { overflow-wrap: anywhere; }
@media (max-width: 800px) { main { margin: 16px; padding: 24px; } }

button:disabled, select:disabled { opacity: 0.6; cursor: wait; }
form { margin-top: 24px; }

The controls use a stable synthetic control ID and expanded ID already designated in the test flag. Fetches are explicit and serialized by the busy state. Unknown, missing, disabled and thrown-error paths show the standard report.

The tests establish application/SDK behavior. The later live browser step establishes that the test deployment returns each actual variant and that the appropriate report renders. Neither check establishes an experiment's statistical result.

5. Mount and test the app

I'll start the app once outside the React component tree and retain Strict Mode. The tests exercise the operation or session behavior separately from the UI.

src/main.jsx
import React,{StrictMode} from 'react';import {createRoot} from 'react-dom/client';
import {App} from './App.jsx';import {initializeAnalytics} from './analytics.js';import './style.css';
initializeAnalytics().then(analytics=>createRoot(document.getElementById('root')).render(<StrictMode><App analytics={analytics}/></StrictMode>));
tests/flags.test.mjs
import {test,expect,vi} from 'vitest';
import {createReportClient,loadReport,reportView,flagKey} from '../src/flags.js';
const user={user_id:'build-vitest-synthetic-user',device_id:'build-vitest-device'};
async function client(options={}){return createReportClient({apiKey:'fake-local-test-key',deploymentKey:'fake-local-deployment-key',instanceName:crypto.randomUUID(),experimentOptions:options});}
test('actual initialized Experiment client reads deterministic expanded/control/missing values without remote calls',async()=>{
 for(const [value,view] of [['expanded','expanded'],['control','control'],['unexpected','control']]){
  const request=vi.fn().mockRejectedValue(Error('Should not fetch'));
  const c=await client({source:'initialVariants',initialVariants:{[flagKey]:{value}},httpClient:{request}});
  expect(reportView(c.experiment.variant(flagKey))).toBe(view);expect(request).not.toHaveBeenCalled();
 }
 const c=await client({httpClient:{request:vi.fn()}});c.experiment.clear();expect(reportView(c.experiment.variant('unknown-flag',{value:'control'}))).toBe('control');
});
test('real SDK fetch caches result; failed refresh retains it, explicit clear prevents stale identity assignment',async()=>{
 const request=vi.fn().mockResolvedValueOnce({status:200,body:JSON.stringify({[flagKey]:{key:flagKey,value:'expanded'}})}).mockRejectedValue(Error('Synthetic offline'));
 const c=await client({httpClient:{request}});
 expect((await loadReport(c,user)).view).toBe('expanded');
 const attempts=request.mock.calls.length;expect(reportView(c.experiment.variant(flagKey))).toBe('expanded');expect(request.mock.calls.length).toBe(attempts);
 expect((await loadReport(c,user)).view).toBe('expanded');
 expect((await loadReport(c,{...user,user_id:'build-vitest-second-user'},{clear:true})).view).toBe('control');
 expect(c.experiment.all()[flagKey]).toBeUndefined();
});
test('blank key mode does not initialize and uses application control fallback',async()=>{
 const c=await createReportClient({apiKey:'',deploymentKey:''});expect(c).toBeNull();expect(await loadReport(c,user)).toEqual({view:'control',assigned:false});
});
Terminal
pnpm test
pnpm build
pnpm dev

Open the local URL printed by Vite.

Verify it worked

Run local tests without .env.local first, then add existing test keys for the separate browser check.

  1. Local real-client tests: Run pnpm test. Confirm three tests pass: deterministic expanded/control/unknown/missing behavior, cached response after a rejected refresh and cleared fallback for another user, and blank-key control. Test responses and initial variants are fixtures, not live assignments.
  2. Blank key build: Build and open the app without keys. It should show the standard report and disabled analytics. The controls keep application control without fetching an assignment.
  3. Real assignments: Set the existing project ingestion/client deployment keys, build and open the app. Use your designated control and expanded test users. Confirm each remote fetch succeeds and the corresponding report is visible. Inspect the actual SDK result, not just a local test fixture.
  4. Exposure: After the assigned report renders, confirm an exposure upload is accepted and processed for the correct flag/variant/user. Automatic exposure is off so reads in tests and all() inspection do not implicitly expose. Keep this separate from asserting a statistical winner.
  5. Existing application: Preserve auth and consent; do not set synthetic demo user IDs on real visitors. Clear cached variants before fetching a different identity when the application requires a safe fallback rather than another user's cached assignment.

Troubleshooting

A refresh failed but the test still gets expanded

That case deliberately establishes cache retention. A resolved fetch is not proof of new remote data. Clear first before another identity when your application must fall back instead of carrying old assignment forward.

The same instance keeps old test variants

Use a fresh Unified instance and distinct instanceName per test. Singleton-style initialization otherwise retains the original client configuration.

The browser receives no report-layout assignment

Use a client deployment containing that flag and a designated test identity. If deploymentKey is omitted, the plugin falls back to the analytics key's default deployment. Do not change production targeting to make a local test pass.

The suite passes without an Amplitude account

The suite controls SDK inputs locally. That is sufficient for its branch/cache assertions, but it does not prove live assignment or ingestion. Run the separate test-project check for those outcomes.

Full code reference

The complete runnable example includes the lockfile. These are the complete application and test files, combined for copying. Keep environment values local.

Full code reference
===== package.json =====
{
  "name": "amplitude-react-feature-flags-vitest",
  "version": "1.0.0",
  "private": true,
  "type": "module",
  "packageManager": "pnpm@10.33.2+sha512.a90faf6feeab71ad6c6e57f94e0fe1a12f5dcc22cd754db40ae9593eb6a3e0b6b12e3540218bb37ae083404b1f2ce6db2a4121e979829b4aff94b99f49da1cf8",
  "engines": {
    "node": ">=22.12.0",
    "pnpm": ">=10.21.0"
  },
  "scripts": {
    "dev": "vite --host 127.0.0.1",
    "build": "vite build",
    "preview": "vite preview --host 127.0.0.1",
    "test": "vitest run"
  },
  "dependencies": {
    "@amplitude/unified": "1.2.1",
    "react": "19.3.1",
    "react-dom": "19.3.1"
  },
  "devDependencies": {
    "vite": "8.3.6",
    "vitest": "5.0.5",
    "jsdom": "31.0.0"
  }
}

===== pnpm-workspace.yaml =====
minimumReleaseAge: 10080
trustPolicy: no-downgrade

===== .gitignore =====
node_modules/
dist/
.env
.env.local
.env.*.local

===== index.html =====
<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Form drop-off demo</title>
  </head>
  <body>
    <div id="root"></div>
    <script type="module" src="/src/main.jsx"></script>
  </body>
</html>

===== .env.example =====
VITE_AMPLITUDE_API_KEY=
VITE_AMPLITUDE_DEPLOYMENT_KEY=
VITE_AMPLITUDE_SERVER_ZONE=US

===== vitest.config.js =====
import { defineConfig } from 'vitest/config';
export default defineConfig({ test: { environment: 'jsdom', restoreMocks: true } });

===== src/flags.js =====
import { createInstance } from '@amplitude/unified';
export const flagKey='report-layout';
export function reportView(variant) { return variant?.value==='expanded'?'expanded':'control'; }
export async function createReportClient({apiKey,deploymentKey,zone='US',instanceName='build-vitest-demo',experimentOptions={}}) {
  if(!apiKey?.trim()||!deploymentKey?.trim())return null;
  const analytics=createInstance();
  await analytics.initAll(apiKey,{instanceName,serverZone:zone==='EU'?'EU':'US',analytics:{autocapture:false,remoteConfig:{fetchRemoteConfig:false}},sessionReplay:{sampleRate:0},engagement:{skip:true},experiment:{deploymentKey,fetchOnStart:false,pollOnStart:false,automaticFetchOnAmplitudeIdentityChange:false,automaticExposureTracking:false,retryFetchOnFailure:false,fetchTimeoutMillis:1000,...experimentOptions}});
  const experiment=analytics.experiment();
  if(!experiment)throw Error('Experiment did not initialize.');
  return {analytics,experiment};
}
export async function loadReport(client,user,{clear=false}={}) {
  if(!client)return {view:'control',assigned:false};
  if(clear)client.experiment.clear();
  await client.experiment.fetch(user);
  const variant=client.experiment.all()[flagKey];
  return {view:reportView(variant),assigned:typeof variant?.value==='string',value:variant?.value??null};
}

===== src/analytics.js =====
import { createReportClient, loadReport, flagKey } from './flags.js';
let ready;
export function initializeAnalytics(){
 if(!ready)ready=createReportClient({apiKey:import.meta.env.VITE_AMPLITUDE_API_KEY,deploymentKey:import.meta.env.VITE_AMPLITUDE_DEPLOYMENT_KEY,zone:import.meta.env.VITE_AMPLITUDE_SERVER_ZONE});
 return ready.then(client=>({status:client?'ready':'disabled',client})).catch(()=>({status:'error',client:null}));
}
export async function chooseReport(client,userId){
 if(!client)return {view:'control',assigned:false};
 client.analytics.setUserId(userId);
 return loadReport(client,{user_id:userId,device_id:client.analytics.getDeviceId()},{clear:true});
}
export function exposeReport(client){client?.experiment.exposure(flagKey);}

===== src/App.jsx =====
import React,{useRef,useState,useEffect} from 'react';
import {chooseReport,exposeReport} from './analytics.js';
export function App({analytics}){
 const [result,setResult]=useState({view:'control',assigned:false}),[busy,setBusy]=useState(false),[token,setToken]=useState(0),[message,setMessage]=useState('Choose an existing designated test identity.');const exposed=useRef(-1);
 useEffect(()=>{if(result.assigned&&exposed.current!==token){exposed.current=token;exposeReport(analytics.client);}},[result,token,analytics.client]);
 async function load(user){if(busy)return;setBusy(true);try{const next=await chooseReport(analytics.client,user);setResult(next);setToken(x=>x+1);setMessage(next.assigned?'Assignment loaded; inspect the result.':'No assignment; safe control.');}catch{setResult({view:'control',assigned:false});setMessage('Fetch failed; safe control.');}finally{setBusy(false);}}
 return <main><h1>Test a flag-gated report</h1><p>The report is a local fixture. These controls use existing test identities; they don't change targeting.</p>
 <button id="control" disabled={busy} onClick={()=>load('build-ios-flags-control-20261029')}>Load control test user</button>
 <button id="expanded" disabled={busy} onClick={()=>load('build-web-flags-demo')}>Load expanded test user</button>
 <p role="status">{message}</p><p>Analytics: <strong>{analytics.status}</strong></p><section id="report" data-view={result.view}><h2>{result.view==='expanded'?'Expanded report':'Standard report'}</h2><p>Saved reports:3</p>{result.view==='expanded'&&<p id="extra-detail">Weekly comparison: +2 reports</p>}</section></main>;
}

===== src/style.css =====
:root { font-family: Helvetica, Arial, sans-serif; color: #000000; background: #F2F4F8; }
body { margin: 0; }
main { max-width: 760px; margin: 40px auto; padding: 32px; background: #FFFFFF; border-radius: 16px; }
h1 { font-size: 36px; }
p { line-height: 1.5; }
.eyebrow { font-size: 12px; letter-spacing: 0.08em; }
nav { display: flex; gap: 20px; flex-wrap: wrap; padding: 16px 0; }
a { color: #0052F2; }
section, aside { border-top: 1px solid #D5D9E0; margin-top: 24px; padding-top: 24px; }
label { display: block; margin-bottom: 8px; }
button, select, [role='button'] { font: inherit; padding: 10px 14px; margin: 0 12px 12px 0; border: 1px solid #000000; border-radius: 6px; color: #000000; background: #FFFFFF; }
button, [role='button'] { cursor: pointer; }
#save-settings { color: #FFFFFF; background: #0052F2; border-color: #0052F2; }
[role='button'] { display: inline-block; }
:focus-visible { outline: 3px solid #0052F2; outline-offset: 3px; }
code { overflow-wrap: anywhere; }
@media (max-width: 800px) { main { margin: 16px; padding: 24px; } }

button:disabled, select:disabled { opacity: 0.6; cursor: wait; }
form { margin-top: 24px; }

===== src/main.jsx =====
import React,{StrictMode} from 'react';import {createRoot} from 'react-dom/client';
import {App} from './App.jsx';import {initializeAnalytics} from './analytics.js';import './style.css';
initializeAnalytics().then(analytics=>createRoot(document.getElementById('root')).render(<StrictMode><App analytics={analytics}/></StrictMode>));

===== tests/flags.test.mjs =====
import {test,expect,vi} from 'vitest';
import {createReportClient,loadReport,reportView,flagKey} from '../src/flags.js';
const user={user_id:'build-vitest-synthetic-user',device_id:'build-vitest-device'};
async function client(options={}){return createReportClient({apiKey:'fake-local-test-key',deploymentKey:'fake-local-deployment-key',instanceName:crypto.randomUUID(),experimentOptions:options});}
test('actual initialized Experiment client reads deterministic expanded/control/missing values without remote calls',async()=>{
 for(const [value,view] of [['expanded','expanded'],['control','control'],['unexpected','control']]){
  const request=vi.fn().mockRejectedValue(Error('Should not fetch'));
  const c=await client({source:'initialVariants',initialVariants:{[flagKey]:{value}},httpClient:{request}});
  expect(reportView(c.experiment.variant(flagKey))).toBe(view);expect(request).not.toHaveBeenCalled();
 }
 const c=await client({httpClient:{request:vi.fn()}});c.experiment.clear();expect(reportView(c.experiment.variant('unknown-flag',{value:'control'}))).toBe('control');
});
test('real SDK fetch caches result; failed refresh retains it, explicit clear prevents stale identity assignment',async()=>{
 const request=vi.fn().mockResolvedValueOnce({status:200,body:JSON.stringify({[flagKey]:{key:flagKey,value:'expanded'}})}).mockRejectedValue(Error('Synthetic offline'));
 const c=await client({httpClient:{request}});
 expect((await loadReport(c,user)).view).toBe('expanded');
 const attempts=request.mock.calls.length;expect(reportView(c.experiment.variant(flagKey))).toBe('expanded');expect(request.mock.calls.length).toBe(attempts);
 expect((await loadReport(c,user)).view).toBe('expanded');
 expect((await loadReport(c,{...user,user_id:'build-vitest-second-user'},{clear:true})).view).toBe('control');
 expect(c.experiment.all()[flagKey]).toBeUndefined();
});
test('blank key mode does not initialize and uses application control fallback',async()=>{
 const c=await createReportClient({apiKey:'',deploymentKey:''});expect(c).toBeNull();expect(await loadReport(c,user)).toEqual({view:'control',assigned:false});
});

Hand it to your agent

Use this prompt to adapt the example to an existing application.

Implementation prompt
Use https://amplitude.com/build/react-feature-flags-vitest and its linked source.
Inspect the current SDK entry point and application flow first. Merge into existing
files; preserve auth, consent, routes, and other instrumentation. Fetch current
Amplitude docs for the installed SDK. Keep the ingestion key in the existing
environment mechanism and never add server secrets to browser code.

Keep actual SDK initialization/variant/cache code in the tests. Control documented
initialVariants and httpClient instead of mocking variant() or all(). Isolate
clients by instance, disable automatic fetch/poll/exposure in test configuration,
and distinguish cached values from fresh assignment. Test unknown/missing flags,
failed refresh, cache clearing before a new identity and blank-key fallback.
Preserve consent/auth; do not use synthetic IDs for production visitors. Verify
existing remote assignments and exposure separately, with no targeting edits.

Test blank-key startup and failure paths as well as success. Confirm real SDK
uploads and processed data separately from local tests. Report changed files and
remaining coverage limits.

What this unlocks

Feature flags can gate an application view while these tests preserve predictable fallback behavior.

Product analytics can measure the relevant business outcome alongside processed [Experiment] Exposure events.

Session replay can add browser context through a separately configured capture policy; this fixture sets replay sampling to zero.

Guides and surveys can support the report experience through their own configuration.

Frequently asked questions

Are the SDK methods mocked?

No. Each test initializes the actual Unified/Experiment client. Vitest controls documented initial variants and the HTTP boundary while SDK variant/cache/clear behavior remains real.

Do these tests need live targeting rules?

No. Local tests are deterministic and need no account or network. The optional browser verification uses existing designated test rules without editing them.

Why clear before an identity change?

A failed fetch can leave cached variants available. Clearing first prevents the previous identity's stored assignment from driving the next identity's view; the test verifies the resulting control fallback.

Next steps

Amplitude is the leading all-in-one analytics platform for building better products. Product and engineering teams use Amplitude to connect product analytics and web analytics with session replay, heatmaps, experimentation, feature flags, and guides and surveys in one unified workflow, with AI agents working across all of it. Learn how Amplitude is building self-improving products with Wave, helping teams turn product data into PRs.

Connect the next event

Make the identity and properties explicit, then verify them in your test project.