{"id":13376,"library":"jest-launchdarkly-mock","title":"Jest LaunchDarkly Mock","description":"jest-launchdarkly-mock is a utility package designed to simplify unit testing of React components that integrate with LaunchDarkly feature flags. It provides a straightforward API to mock feature flag states and the LaunchDarkly client within Jest test environments, specifically for applications using the `launchdarkly-react-client-sdk`. The current stable version is 2.2.1, with releases occurring periodically to address bugs and support new features of the underlying LaunchDarkly SDKs. Key differentiators include its tight integration with Jest for mocking, its explicit support for React SDK hooks like `useFlags`, and its ability to simulate client-side LaunchDarkly behavior without network calls. It supports LaunchDarkly's custom contexts feature introduced in v2.0.0, which evolved from the 'users' concept. The library is primarily used in TypeScript projects, shipping with its own type definitions.","status":"active","version":"2.2.1","language":"javascript","source_language":"en","source_url":"https://github.com/launchdarkly/jest-launchdarkly-mock","tags":["javascript","jest","launchdarkly","mock","unit","test","feature","flags","typescript"],"install":[{"cmd":"npm install jest-launchdarkly-mock","lang":"bash","label":"npm"},{"cmd":"yarn add jest-launchdarkly-mock","lang":"bash","label":"yarn"},{"cmd":"pnpm add jest-launchdarkly-mock","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Peer dependency for integration with LaunchDarkly in React applications.","package":"launchdarkly-react-client-sdk","optional":false},{"reason":"Peer dependency for React applications. Requires React 17 or newer.","package":"react","optional":false}],"imports":[{"note":"Used to set specific flag values for a test case. Ensure Jest's `setupFiles` is configured correctly.","wrong":"const { mockFlags } = require('jest-launchdarkly-mock')","symbol":"mockFlags","correct":"import { mockFlags } from 'jest-launchdarkly-mock'"},{"note":"A Jest mock object for the LaunchDarkly client, allowing assertion of client method calls like `identify`.","wrong":"const ldClientMock = require('jest-launchdarkly-mock').ldClientMock","symbol":"ldClientMock","correct":"import { ldClientMock } from 'jest-launchdarkly-mock'"},{"note":"Essential to call in `beforeEach` to clear mock states between tests, preventing contamination.","wrong":"import resetLDMocks from 'jest-launchdarkly-mock/reset'","symbol":"resetLDMocks","correct":"import { resetLDMocks } from 'jest-launchdarkly-mock'"}],"quickstart":{"code":"import { render, fireEvent } from '@testing-library/react';\nimport { mockFlags, ldClientMock, resetLDMocks } from 'jest-launchdarkly-mock';\nimport React from 'react';\n\n// Assume Button component is defined elsewhere and uses useFlags or withLDConsumer\nconst Button = () => {\n  // In a real app, this would use LaunchDarkly hooks/HOCs\n  const devTestFlag = true; // Simplified for this quickstart\n  const onClick = () => {\n    // Simulate identify call\n    if (ldClientMock && ldClientMock.identify) {\n      ldClientMock.identify({ key: 'user-key-123' });\n    }\n  };\n\n  return (\n    <button data-testid=\"test-button\" onClick={onClick}>\n      {devTestFlag ? 'Feature On' : 'Feature Off'}\n    </button>\n  );\n};\n\ndescribe('Button component with LaunchDarkly mocks', () => {\n  beforeEach(() => {\n    // Clears all previous flag mocks and client mock calls\n    resetLDMocks();\n  });\n\n  test('should show \"Feature On\" when devTestFlag is true', () => {\n    // Arrange: Set a specific flag state\n    mockFlags({ devTestFlag: true });\n\n    // Act: Render the component\n    const { getByTestId } = render(<Button />);\n\n    // Assert: Check the component's output based on the mocked flag\n    expect(getByTestId('test-button')).toHaveTextContent('Feature On');\n  });\n\n  test('should call ldClientMock.identify on button click', () => {\n    // Arrange: Set flag and ensure identify mock is available\n    mockFlags({ devTestFlag: false });\n    \n    // Act: Render and click the button\n    const { getByTestId } = render(<Button />);\n    fireEvent.click(getByTestId('test-button'));\n\n    // Assert: Verify that the ldClientMock.identify function was called with the expected arguments\n    expect(ldClientMock.identify).toHaveBeenCalledWith({ key: 'user-key-123' });\n  });\n});","lang":"typescript","description":"Demonstrates how to mock feature flag states and assert LaunchDarkly client interactions within a Jest test using `mockFlags`, `ldClientMock`, and `resetLDMocks`."},"warnings":[{"fix":"Review the migration guide for `launchdarkly-react-client-sdk` v3.0.0 and update your mock `identify` and `track` calls to use context objects instead of user objects.","message":"Version 2.0.0 introduced support for LaunchDarkly's 'custom contexts' feature, which replaces the older 'users' concept. If you're upgrading from v1.x, you will need to adjust your tests to use the new context structure where applicable, aligning with the `launchdarkly-react-client-sdk` v3.0.0 changes.","severity":"breaking","affected_versions":">=2.0.0"},{"fix":"Ensure your tests explicitly call `mockFlags` to set desired flag states. If you were relying on implicit defaults, those tests might now fail. This primarily affects `useFlags` hook usage.","message":"Prior to v2.1.0, the `useFlags` mock might have returned different default values. Since v2.1.0, `useFlags` now returns an empty object by default, which aligns with its actual implementation in the SDK.","severity":"breaking","affected_versions":">=2.1.0"},{"fix":"Verify that your application uses `launchdarkly-react-client-sdk`. If using the plain JS SDK, a different mocking strategy or library will be required.","message":"jest-launchdarkly-mock is designed specifically for mocking components that interact with the `launchdarkly-react-client-sdk`. It is not compatible with the plain `launchdarkly-js-client-sdk` or other LaunchDarkly SDKs.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Add `'jest-launchdarkly-mock'` to the `setupFiles` array in your `jest.config.js` or equivalent Jest configuration file.","message":"It is crucial to include `jest-launchdarkly-mock` in Jest's `setupFiles` configuration. Without this, the global mocks will not be properly initialized, leading to errors like `ldClientMock` or `mockFlags` being undefined.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Upgrade your React version to `17.0.2` or higher, or use an older version of `jest-launchdarkly-mock` (e.g., 1.0.3 or earlier) that has a less restrictive React peer dependency.","message":"The peer dependency for React was updated to `>=17.0.2` in versions 1.0.5 and 1.0.6. If you are using an older version of React, you might encounter peer dependency warnings or runtime issues.","severity":"gotcha","affected_versions":">=1.0.5"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"fix":"Ensure `jest-launchdarkly-mock` is listed in your `jest.config.js` `setupFiles` array and `resetLDMocks()` is called in a `beforeEach` hook.","cause":"The `ldClientMock` was not properly initialized or `ldClientMock.identify` was accessed before a test ran or before `jest-launchdarkly-mock` was loaded.","error":"TypeError: Cannot read properties of undefined (reading 'identify')"},{"fix":"Verify that `jest-launchdarkly-mock` is present in your Jest `setupFiles` configuration. Also, ensure your component is rendered within the scope of the mock.","cause":"The React context or hooks related to LaunchDarkly were not mocked correctly, likely due to `jest-launchdarkly-mock` not being configured in Jest's `setupFiles`.","error":"Error: Uncaught [TypeError: Cannot read properties of undefined (reading 'useFlags')]"},{"fix":"Check your React peer dependency version (should be `>=17.0.2`) and ensure `jest-launchdarkly-mock` is correctly configured in `setupFiles`. Consider upgrading both `react` and `launchdarkly-react-client-sdk`.","cause":"This error can occur if the `launchdarkly-react-client-sdk` is not properly mocked or if React versions are mismatched, leading to incorrect hook behavior.","error":"Invariant Violation: Invalid hook call. Hooks can only be called inside of the body of a function component."}],"ecosystem":"npm","meta_description":null,"install_score":null,"install_tag":null,"quickstart_score":null,"quickstart_tag":null,"pypi_latest":null,"cli_name":"","cli_version":null}