Write unit tests with the Flags SDK
Test your application with fixed flag values. Replace an exported flag function with a mock, a replacement function whose return value you control.
These tests work with any flag provider connected through the Flags SDK.
Before you start
Use an application with the Flags SDK. Configure Vitest or Jest to run the tests.
These examples test a function that uses a flag. Use your framework's component testing tools when you also need to check rendered output.
These tests do not require FLAGS_SECRET because the mock replaces flag evaluation.
Define the flag
Declare a boolean flag in a separate file:
An existing flag can use an adapter instead of decide. An adapter connects the Flags SDK to your flag provider. The tests below replace the exported function in either case.
Add application behavior
Create a function that selects the dashboard title from the flag value:
Keep the flag in a separate file from the code under test. Vitest or Jest can then replace the imported flag function.
Test both values with Vitest
Use vi.mock() to replace the imported flag function. Reset the mock before each test, then set the required return value:
Run the test:
Both tests should pass. Each test checks the title for one flag value without reading request data or calling a provider.
mockReset() removes the previous return value and call history. Set the required return value again in each test. mockClear() only removes call history and keeps the previous implementation.
See Vitest module mocking for details about module factories and import handling.
Test both values with Jest
Use this version instead of the Vitest test. Configure Jest to transform TypeScript imports to CommonJS, the module format used by require().
Run the test:
The explicit function type lets the mock return a boolean or a Promise<boolean>.
Both tests should pass. For native ECMAScript modules (ESM), follow Jest's ESM mocking instructions.
Test additional flag values
Use the same test pattern for flags that return strings or numbers. Add a test for each value that produces a different result.
When several flags affect the same result, add a mock function for each flag to vi.mock() or jest.mock(). Set all required flag values before you call the application code.
When to use end-to-end tests
End-to-end tests use a browser to check the running application. Use these tests to check flag values in pages that depend on request headers or cookies.
The SvelteKit createHandle() hook supplies request headers and cookies for flag evaluation. Tests that call the real flag must use this hook or pass a Request directly to the flag function.
Next steps
Write end-to-end tests with flag overrides