Unit testing
Learn how to write unit tests for your integration.
The Next.js SDK includes a test mode that makes it easy to develop and test your integration by simulating SDK behavior without sending real API requests.
Here is what you need to check:
- Make sure your tracking calls are triggered correctly
- Verify you have defined fallbacks for your content
- Ensure you are handling evaluation errors.
In the following sections, we will go through each of these points in detail.
Enable test mode
Since everything in the SDK is event-driven, the best way to test your integration is to listen for events and make assertions on them.
Even imperative methods — like identify, which identifies users, or user.edit, used to edit user profiles — are just syntactic sugar for triggering events. This approach simplifies testing because you do not have to rely on mocking, which usually results in brittle tests.
To make testing easier, the SDK provides a test mode that you can enable in your test environment.
If you're using Jest or any other test framework that sets the NODE_ENV=test, it should just work out of the box.
By default, the SDK auto-detects test environments based on the NODE_ENV.
To explicitly enable test mode, pass test as true when initializing the SDK, or set the NEXT_PUBLIC_CROCT_TEST environment variable to true.
Once enabled, the SDK uses a fake transport layer that simulates successful calls, so you do not need to mock the network requests.
Write tests
With test mode enabled, you can write assertions on the events triggered by your integration.
Suppose you want to check if your application correctly collects user interests. The code you want to test might look like this:
croct.user.edit().add('interest', 'tests').save()
This code triggers a userProfileChanged event with your changes to the user profile, which you can use to make assertions.
Here is an example of how you can write a test for this code using Jest:
import {render, screen} from '@testing-library/react';import userEvent from '@testing-library/user-event';import {CroctProvider} from '@croct/plug-next/CroctProvider';import croct from '@croct/plug';import LoginForm from './LoginForm';it('should add an interest to the user profile', async () => {render(<CroctProvider appId="00000000-0000-0000-0000-000000000000"><LoginForm /></CroctProvider>);const listener = jest.fn();croct.tracker.addListener(listener);await userEvent.click(screen.getByText('Login'));expect(listener).toHaveBeenCalledWith(expect.objectContaining({status: 'confirmed',event: {type: 'userProfileChanged',patch: {operations: [{path: 'interest',type: 'add',value: 'tests',},],},},}),);});
You can find more details about the available events in the Event reference.
Content retrieval testing
For testing if your content renders correctly, you can intercept the call to the fetch method and mock the response.
Suppose you have a <HomeHero> component like this:
import {useContent} from '@croct/plug-next';export function HomeHero({fallbackContent}) {const content = useContent('home-hero@1', {initial: null,fallback: fallbackContent,});if (content === null) {return <div>✨ Personalizing...</div>;}return (<div><h1>{content.title}</h1><p>{content.subtitle}</p><a href={content.button.link}>{content.button.label}</a></div>);}
Here is an example of how you can test the personalized content using Jest and React Testing Library:
import {act, render, screen, waitFor} from '@testing-library/react';import {CroctProvider} from '@croct/plug-next';import croct from '@croct/plug';import HomeHero from './HomeHero';it('should render the personalized content on success', async () => {const fallbackContent = {title: 'Fallback title',subtitle: 'Fallback subtitle',button: {label: 'Fallback button',link: 'https://croct.com',},};const content = {title: 'Banner title',subtitle: 'Banner subtitle',button: {label: 'Button',link: 'https://croct.com',},};const fetchContent = jest.spyOn(croct, 'fetch');fetchContent.mockResolvedValue({content: content,});render(<CroctProvider appId="00000000-0000-0000-0000-000000000000"><HomeHero fallbackContent={fallbackContent} /></CroctProvider>);expect(fetchContent).toHaveBeenCalledWith('home-hero@1', {});// Flush promisesawait act(() => Promise.resolve());await waitFor(() => {expect(screen.getByText(content.title)).toBeInTheDocument();});expect(screen.getByText(content.subtitle)).toBeInTheDocument();expect(screen.getByText(content.button.label)).toBeInTheDocument();});
To test your fallbacks, you can mock a failed response:
import {act, render, screen, waitFor} from '@testing-library/react';import {CroctProvider} from '@croct/plug-next/CroctProvider';import croct from '@croct/plug';import HomeHero from './HomeHero';it('should render the fallback content on error', async () => {const fallbackContent = {title: 'Fallback title',subtitle: 'Fallback subtitle',button: {label: 'Fallback button',link: 'https://croct.com',},};const fetchContent = jest.spyOn(croct, 'fetch');fetchContent.mockRejectedValue(new Error('Failed to fetch content'));render(<CroctProvider appId="00000000-0000-0000-0000-000000000000"><HomeHero fallbackContent={fallbackContent} /></CroctProvider>);expect(fetchContent).toHaveBeenCalledWith('home-hero@1', {});// Flush promisesawait act(() => Promise.resolve());await waitFor(() => {expect(screen.getByText(fallbackContent.title)).toBeInTheDocument();});});
Query evaluation testing
To test if your queries are working as expected, you can follow the same approach as for content retrieval testing.
Suppose you have a <Greetings> component like this:
import {useEvaluation} from '@croct/plug-next';export function Greetings() {const returning = useEvaluation('user is returning', {initial: null,fallback: false,});if (returning === null) {return <div>✨ Personalizing...</div>;}return <h1>{returning ? 'Welcome back!' : 'Welcome!'}</h1>;}
Here is an example of how you can test the query evaluation using Jest and React Testing Library:
import {render, screen, waitFor} from '@testing-library/react';import {CroctProvider} from '@croct/plug-next/CroctProvider';import croct from '@croct/plug';import Greetings from './Greetings';it('should render the content based on the query result', async () => {const evaluateQuery = jest.spyOn(croct, 'evaluate');evaluateQuery.mockResolvedValue({result: true,});render(<CroctProvider appId="00000000-0000-0000-0000-000000000000"><Greetings /></CroctProvider>);expect(evaluateQuery).toHaveBeenCalledWith('user is returning');await waitFor(() => {expect(screen.getByText('Welcome back!')).toBeInTheDocument();});});
To test your fallbacks, you can mock a failed response:
import {render, screen, waitFor} from '@testing-library/react';import {CroctProvider} from '@croct/plug-next/CroctProvider';import croct from '@croct/plug';import Greetings from './Greetings';it('should render the fallback content on error', async () => {const evaluateQuery = jest.spyOn(croct, 'evaluate');evaluateQuery.mockRejectedValue(new Error('Failed to evaluate query'));render(<CroctProvider appId="00000000-0000-0000-0000-000000000000"><Greetings /></CroctProvider>);expect(evaluateQuery).toHaveBeenCalledWith('user is returning');await waitFor(() => {expect(screen.getByText('Welcome!')).toBeInTheDocument();});});