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:Step 2: Install Dynamic Labs SDK
Install the required Dynamic Labs packages:Step 3: Add Dynamic to Your Application
Configure the Layout
Opensrc/app/layout.tsx
and add the DynamicContextProvider
. Replace <YOUR_ENVIRONMENT_ID>
with your actual environment ID from the Dynamic dashboard:
Add the DynamicWidget
Opensrc/app/page.tsx
and add the DynamicWidget
component:
Step 4: Configure Jest for Testing
Install Testing Dependencies
Install Jest and React Testing Library along with necessary type definitions:Initialize Jest Configuration
Create a basic Jest configuration file:Configure Jest for Next.js
Create ajest.config.ts
file in your project root with the following configuration:
Set Up Jest Custom Matchers
Create ajest.setup.ts
file in your project root to configure testing utilities:
Update Jest Configuration
Update yourjest.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
Modifysrc/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 yourpackage.json
:
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