Skip to content

reactive/data-client / .agents/skills/data-client-react-testing

data-client-react-testing

Verified

Test React code that uses @data-client/react: components and hooks that fetch or change data, with mocked responses for loading, error, mutation and polling cases. Covers renderDataHook, MockResolver and fixtures.

references/renderDataHook.md

View on GitHub
<!-- Generated by `yarn build:skills` from docs/core/api/renderDataHook.md (react). Edit the source doc, not this file. -->

# renderDataHook()

`renderDataHook()` renders a hook that uses Reactive Data Client for a test. It renders the hook inside a
`DataProvider` and a `<Suspense/>` boundary. With React 18 or later, it wraps
[@testing-library/react](https://testing-library.com/docs/react-testing-library/api#renderhook)'s `renderHook()` in a DOM
environment, or [@testing-library/react-native](https://github.com/callstack/react-native-testing-library)'s on React Native. Otherwise it uses
[@testing-library/react-hooks](https://react-hooks-testing-library.com/reference/api#renderhook-options). All of them
give the result documented below.

> **Note**
>
> Each call to `renderDataHook()` creates a new store and new manager instances, so no cache or manager state carries over
> between calls.

<details>

<summary>Type</summary>

```typescript
type RenderDataHook = {
  <P, R, T = any>(
    callback: (props: P) => R,
    options?: {
      initialProps?: P;
      initialFixtures?: Fixture[];
      resolverFixtures?: (Fixture | Interceptor<T>)[];
      getInitialInterceptorData?: () => T;
      managers?: () => Manager[];
      wrapper?: React.ComponentType;
    },
  ): {
    rerender: (props?: Props) => void;
    result: {
      current: Result;
      error?: Error;
    };
    unmount: () => void;
    controller: Controller;
    cleanup(): void;
    allSettled(): Promise<unknown>;
    /* @deprecated */
    waitForNextUpdate: (options?: waitForOptions) => Promise<void>;
    waitFor<T>(
      callback: () => Promise<T> | T,
      options?: waitForOptions,
    ): Promise<T>;
  };
  /** @deprecated use cleanup() from the renderDataHook() return value */
  cleanup(): void;
  /** @deprecated use allSettled() from the renderDataHook() return value */
  allSettled(): Promise<unknown>;
};
```

</details>

## Usage

```typescript
import { useSuspense } from '@data-client/react';
import { renderDataHook } from '@data-client/test';
import { Article, ArticleResource } from './resources/Article';

const response = {
  id: 5,
  title: 'hi ho',
  content: 'whatever',
  tags: ['a', 'best', 'react'],
};

it('useSuspense() should render the response', async () => {
  const { result, waitFor } = renderDataHook(
    () => {
      return useSuspense(ArticleResource.get, { id: 5 });
    },
    {
      initialFixtures: [
        {
          endpoint: ArticleResource.get,
          args: [{ id: 5 }],
          response,
        },
      ],
    },
  );
  expect(result.current instanceof Article).toBe(true);
  expect(result.current.title).toBe(response.title);
});
```

## Arguments

### callback

Hook to run inside React. Return value will become available in [result.current](#result)

### options.initialFixtures

Can be used to prime the cache if test expects cache values to already be filled. Takes an
[array of fixtures](./Fixtures.md)

This has the same effect as initializing [\<DataProvider />](https://dataclient.io/docs/api/DataProvider) with [mockInitialState()](./mockInitialState.md)

### options.resolverFixtures

These [fixtures or interceptors](./Fixtures.md) are used to resolve any new requests. This is most useful for mocking imperative fetches like mutations, but can also allow testing suspending states or transitions.

Works by adding [MockResolver](./MockResolver.md) as a wrapper.

### options.getInitialInterceptorData

Function that initializes the `this` attribute for all interceptors.

### options.managers

Returns the [Managers](https://dataclient.io/docs/api/Manager) to use. Each `renderDataHook()` call calls it once, so each test gets
new instances. The result replaces the default [NetworkManager](https://dataclient.io/docs/api/NetworkManager) and
[SubscriptionManager](https://dataclient.io/docs/api/SubscriptionManager). It must include a `NetworkManager`; add a `SubscriptionManager`
when the test needs subscriptions.

Put a Manager before `NetworkManager` to see `fetch` actions, because `NetworkManager` handles them without
passing them on.

```ts
import type { Manager } from '@data-client/react';
import { NetworkManager, useController } from '@data-client/react';
import { renderDataHook } from '@data-client/test';
import { TodoResource } from './resources/Todo';

it('logs every action', async () => {
  const types: string[] = [];
  const logger: Manager = {
    middleware: () => next => action => {
      types.push(action.type);
      return next(action);
    },
    cleanup() {},
  };
  const { controller } = renderDataHook(() => useController(), {
    managers: () => [logger, new NetworkManager()],
  });
  await controller.setResponse(
    TodoResource.get,
    { id: 5 },
    { id: 5, title: 'hi', completed: false },
  );
  expect(types).toEqual(['rdc/setresponse']);
});
```

### options.initialProps

The initial values to pass to the callback function

### options.wrapper

Pass a React Component as the wrapper option to have it rendered around the inner element

## Returns

### controller

[Controller](https://dataclient.io/docs/api/Controller) to dispatch imperative effects

```ts
import { act } from '@testing-library/react';
import { useSuspense } from '@data-client/react';
import { renderDataHook } from '@data-client/test';
import { Todo, TodoResource } from './resources/Todo';

it('should update', async () => {
  const id = 5;
  const payload = { title: 'first item', id, completed: false };
  const { result, controller } = renderDataHook(
    () => {
      return useSuspense(TodoResource.getList);
    },
    {
      initialFixtures: [
        {
          endpoint: TodoResource.getList,
          args: [],
          response: [payload],
        },
      ],
      resolverFixtures: [
        {
          endpoint: TodoResource.update,
          response: ({ id }, body) => ({ ...body, id }),
        },
      ],
    },
  );
  expect(result.current).toEqual([Todo.fromJS(payload)]);
  await act(async () => {
    await controller.fetch(
      TodoResource.update,
      { id },
      { title: 'updated title' },
    );
  });
  expect(result.current[0].title).toBe('updated title');
});
```

### cleanup()

Cleans up the managers of this render. Reactive Data Client's internals use real timers to avoid race conditions, so
this matters when you mock timers.

Cleanup runs after each test in an `afterEach` hook, like `@testing-library/react`. Call it yourself only to control
its order in a test. For example, clean up before you switch from fake timers to real timers:

```ts
it('should handle polling', async () => {
  jest.useFakeTimers();
  const { result, cleanup } = renderDataHook(/* ... */);
  // ... assertions ...
  cleanup(); // must run while fake timers are still active
  jest.useRealTimers();
});
```

### allSettled()

Returns a promise that resolves when all inflight requests of this render complete.

> **Warning: Deprecated**
>
> `renderDataHook.cleanup()` and `renderDataHook.allSettled()` act only on the latest render. Use the ones each
> `renderDataHook()` call returns.

### result

- `current` (`any`) - the return value of the `callback` function
- `error` (`Error`) - the error that was thrown if the `callback` function threw an error during rendering

### waitFor

Returns a `Promise` that resolves if the provided callback executes without exception and returns a truthy or undefined value. It is safe to use the result of renderDataHook in the callback to perform assertion or to test values.

### waitForNextUpdate

> **Warning: Deprecated**
>
> Use waitFor instead

Returns a `Promise` that resolves the next time the hook renders, commonly when state is updated as the result of a asynchronous action.

### rerender

(`function([newProps])`) - function to rerender the test component including any hooks called in the `callback` function. If `newProps` are passed, the will replace the `initialProps` passed the the `callback` function for future renders.

### unmount

(`function()`) - function to unmount the test component, commonly used to trigger cleanup effects for `useEffect` hooks.

## Examples

```typescript
import { useSuspense } from '@data-client/react';
import { renderDataHook } from '@data-client/test';
import { Article, ArticleResource } from './resources/Article';

const response = {
  id: 5,
  title: 'hi ho',
  content: 'whatever',
  tags: ['a', 'best', 'react'],
};

it('should resolve useSuspense()', async () => {
  const { result, waitFor, controller } = renderDataHook(
    () => {
      return useSuspense(ArticleResource.get, response);
    },
    {
      resolverFixtures: [
        {
          endpoint: ArticleResource.get,
          response: ({ id }) => ({ ...response, id }),
        },
        {
          endpoint: ArticleResource.partialUpdate,
          response: ({ id }, body) => ({ ...body, id }),
        },
      ],
    },
  );
  // this indicates suspense
  expect(result.current).toBeUndefined();
  await waitFor(() => expect(result.current).toBeDefined());
  expect(result.current instanceof Article).toBe(true);
  expect(result.current.title).toBe(response.title);
  await controller.fetch(
    ArticleResource.partialUpdate,
    { id: response.id },
    { title: 'updated title' },
  );
  expect(result.current.title).toBe('updated title');
});
```
finishing-a-development-branchobra/superpowersUse when implementation is complete, all tests pass, and you need to decide how to integrate the workStars: 319kUpdated Claude CodeCodexVerifiedInstall
systematic-debuggingobra/superpowersUse when encountering any bug, test failure, or unexpected behavior, before proposing fixesStars: 319kUpdated Claude CodeCodexVerifiedInstall
test-driven-developmentobra/superpowersUse when implementing any feature or bugfix, before writing implementation codeStars: 319kUpdated Claude CodeCodexVerifiedInstall
skill-creatoranthropics/skillsCreate new skills, modify and improve existing skills, and measure skill performance. Use when users want to create a skill from scratch, edit, or optimize an existing skill, run evals to test a skill, benchmark skill performance with variance analysis, or optimize a skill's description for better triggering accuracy.Stars: 196kUpdated Claude CodeCodexVerifiedInstall