This guide walks you through setting up Jest testing for a Next.js application that uses the Dynamic Labs SDK. You’ll learn how to properly mock Dynamic components and hooks to write effective unit tests.
Prerequisites
- Node.js installed on your machine
- Basic familiarity with Next.js and React Testing Library
- A Dynamic Labs account with an environment ID
Step 1: Create a New Next.js Project
First, create a new Next.js application using the latest version:
Follow the prompts to set up your project with TypeScript and other preferred options.
Step 2: Install Dynamic Labs SDK
Install the required Dynamic Labs packages:
Step 3: Add Dynamic to Your Application
Open src/app/layout.tsx and add the DynamicContextProvider. Replace <YOUR_ENVIRONMENT_ID> with your actual environment ID from the Dynamic dashboard:
Open src/app/page.tsx and add the DynamicWidget component:
Install Testing Dependencies
Install Jest and React Testing Library along with necessary type definitions:
Initialize Jest Configuration
Create a basic Jest configuration file:
Create a jest.config.ts file in your project root with the following configuration:
Set Up Jest Custom Matchers
Create a jest.setup.ts file in your project root to configure testing utilities:
Update Jest Configuration
Update your jest.config.ts to include the setup file:
Step 5: Write Tests for Dynamic Components
Test the Layout Component
Create a __tests__/layout.test.jsx file to test your layout:
Test the Page Component
Create a __tests__/page.test.jsx file to test your page:
Step 6: Test Components Using Dynamic Hooks
Update Your Page to Use Hooks
Modify src/app/page.tsx to use Dynamic hooks for displaying user information:
Test with Mocked Hooks
Update __tests__/page.test.jsx to properly mock and test Dynamic hooks:
Understanding the Mocking Strategy
When testing components that use the Dynamic Labs SDK, the key approach is to mock the SDK modules and hooks:
Mock the Entire Module
Mock @dynamic-labs/sdk-react-core to replace all components and hooks with Jest mock functions:
Mock Individual Hooks
Each hook can return different values for different test scenarios:
Running Your Tests
Add a test script to your package.json:
Run your tests:
Summary
You’ve successfully set up Jest testing for your Next.js application with Dynamic Labs SDK. The key takeaways are:
- Mock the entire
@dynamic-labs/sdk-react-core module to replace components and hooks
- Use
jest.fn() to create mock implementations that can return different values for different test scenarios
- Configure Jest custom matchers from
@testing-library/jest-dom for better test assertions
This testing approach allows you to thoroughly test your application’s behavior without needing to connect to actual wallets or authenticate real users during your test runs. Last modified on March 30, 2026