Documentation Index
Fetch the complete documentation index at: https://launchdarkly-preview.mintlify.app/llms.txt
Use this file to discover all available pages before exploring further.
Overview
This guide explains how to unit test LaunchDarkly React applications with Jest. jest-launchdarkly-mock allows you to simulate, or “mock,” flag evaluations locally. This lets you verify testing behavior happens correctly, while also letting you use the React SDK in your React application.The jest-launchdarkly-mock package is only compatible with the React Web SDK.
Migrating from users to contexts
The 2.x version of jest-launchdarkly-mock only operates on contexts. When you migrate from version 1.x, replacegetUser with getContext and remove all references to the alias function because it has been removed.
Getting started
First, install jest-launchdarkly-mock with a package manager:Usage
The jest-launchdarkly-mock package contains three exports to help unit test LaunchDarkly in your app:mockFlags, to mock flags at the start of each test case. This only mocks flags returned by theuseFlagshook.resetLDMocks, to reset.ldClientMock, to mock theldClientin the React Web SDK.To learn more, read the Readme.
Mocking flags
Use themockFlags function to mock flags. This only mocks flags returned by the useFlags hook. Pass an LDFlagSet containing the flag keys and values you want to mock. You can use camelCase, snake_case, kebab-case, or unchanged flag keys when mocking flags.
Here’s how:
Resetting mocks
In the setup step of your test suite, useresetLDMocks() to reset all mocks and ensure each test runs with a clean slate. This function resets all mocked flags and ldClientMock.Here’s how:
Testing `ld
ClientYou can use ldClientMockto write tests involving theldClient. This is a Jest mock of the ldClient. All functions of ldClientMockare also Jest mocks.For example, if you have a button that callsldClient.identifyon click, then you can write an assertion usingldClientMock`.Here’s how: