# 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`](/reference/sdk/javascript/api/plug/identify), which identifies users, or [`user.edit`](/reference/sdk/javascript/api/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.

> **Automatic test mode detection**
>
> If you're using [Jest](https://jestjs.io) 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`](../api/components/croct-provider#test-prop) as `true` when initializing the SDK, or set the [`NEXT_PUBLIC_CROCT_TEST`](../api/environment-variables#next_public_croct_test-prop) 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:

```ts
croct.user.edit()
  .add('interest', 'tests')
  .save()
```

This code triggers a [`userProfileChanged`](/reference/event/types/user-account/user-profile-changed) 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](https://jestjs.io):

**JavaScript**

```jsx
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',
          },
        ],
      },
    },
  }),
);
});
```

**TypeScript**

```tsx
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 type {EventInfo} from '@croct/plug/sdk/tracking';
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<Partial<EventInfo<'userProfileChanged'>>>({
    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](/reference/event/overview#event-types).

### Content retrieval testing

For testing if your content renders correctly, you can intercept the call to the [`fetch`](/reference/sdk/javascript/api/plug/fetch) method and mock the response.

The TypeScript examples below use the [`SlotContent`](../api/types/slot-content) type to ensure mock data matches the slot's schema.

Suppose you have a `<HomeHero>` component like this:

**JavaScript**

```jsx
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>
);
}
```

**TypeScript**

```tsx
import type {ReactElement} from 'react';
import {useContent} from '@croct/plug-next';
import type {SlotContent} from '@croct/plug-next';

type HomeHeroProps = {
fallbackContent: SlotContent<'home-hero'>;
};

export function HomeHero({fallbackContent}: HomeHeroProps): ReactElement {
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](https://jestjs.io) and [React Testing Library](https://testing-library.com):

**JavaScript**

```jsx
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();
});
```

**TypeScript**

```tsx
import {act, render, screen, waitFor} from '@testing-library/react';
import {CroctProvider} from '@croct/plug-next';
import type {SlotContent} from '@croct/plug-next';
import croct from '@croct/plug';
import HomeHero from './HomeHero';

it('should render the personalized content on success', async () => {
const fallbackContent: SlotContent<'home-hero'> = {
  title: 'Fallback title',
  subtitle: 'Fallback subtitle',
  button: {
    label: 'Fallback button',
    link: 'https://croct.com',
  },
};

const content: SlotContent<'home-hero'> = {
  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:

**JavaScript**

```jsx
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();
});
});
```

**TypeScript**

```tsx
import {act, render, screen, waitFor} from '@testing-library/react';
import {CroctProvider} from '@croct/plug-next/CroctProvider';
import type {SlotContent} from '@croct/plug-next';
import croct from '@croct/plug';
import HomeHero from './HomeHero';

it('should render the fallback content on error', async () => {
const fallbackContent: SlotContent<'home-hero'> = {
  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:

**JavaScript**

```jsx
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>;
}
```

**TypeScript**

```tsx
import type {ReactElement} from 'react';
import {useEvaluation} from '@croct/plug-next';

export function Greetings(): ReactElement {
const returning = useEvaluation<boolean|null>('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](https://jestjs.io) and [React Testing Library](https://testing-library.com):

**Greetings.test.jsx**

```jsx
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**

```jsx
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();
});
});
```
