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.

Croct's mascot amazed
Automatic test mode detection

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.

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 :

LoginForm.test.jsx
12345678910111213141516171819202122232425262728293031323334353637
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:

HomeHero.jsx
1234567891011121314151617181920
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 :

HomeHero.test.jsx
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
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 promises
await 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:

HomeHero.test.jsx
12345678910111213141516171819202122232425262728293031323334
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 promises
await 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:

Greetings.jsx
1234567891011121314
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 :

Greetings.test.jsx
123456789101112131415161718192021222324
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:

Greetings.test.jsx
12345678910111213141516171819202122
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();
});
});