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/unit-testing-hooks.md

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

# Unit testing hooks

> **Warning**
>
> Be careful with [jest.mock](https://jestjs.io/docs/jest-object#jestmockmodulename-factory-options) on Reactive Data
> Client modules. A mock that removes exports causes errors that are hard to trace, such as
> `TypeError: Class extends value undefined is not a function or null`.
>
> Use a [partial mock](https://jestjs.io/docs/mock-functions#mocking-partials) instead, or better,
> [mockResolvedValue](https://jestjs.io/docs/mock-functions#mocking-modules) on your endpoints.

[renderDataHook()](./renderDataHook.md) renders a 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://github.com/testing-library/react-hooks-testing-library).

`result.current` is `undefined` until the hook first returns. If it suspends again later, `result.current` keeps the last
value. `result.error` holds any error the hook throws.

Each call to `renderDataHook()` creates a new store and new manager instances, so no state carries over between tests.
Use `initialFixtures` to prime the cache. Cleanup runs automatically after each test.

### Polyfill fetch

Jest's `jsdom` environment has no global `fetch`, even on Node 18 and later. Add a polyfill:

```bash
npm install --save-dev whatwg-fetch
```

### Jest

```js
// jest.config.js
module.exports = {
  // other things
  setupFiles: ['./testSetup.js'],
};
```

```js
// testSetup.js
require('whatwg-fetch');
```

### Example

**@data-client/react**

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

describe('useSuspense()', () => {
  beforeEach(() => {
    nock(/.*/)
      .persist()
      .defaultReplyHeaders({
        'Access-Control-Allow-Origin': '*',
        'Content-Type': 'application/json',
      })
      .options(/.*/)
      .reply(200)
      .get(`/article/0`)
      .reply(403, {});
  });

  afterEach(() => {
    nock.cleanAll();
  });

  it('should throw errors on bad network', async () => {
    const { result, waitFor } = renderDataHook(() => {
      return useSuspense(ArticleResource.get, {
        title: '0',
      });
    });
    expect(result.current).toBeUndefined();
    await waitFor(() => expect(result.current).toBeDefined());
    expect(result.error).toBeDefined();
    expect((result.error as any).status).toBe(403);
  });
});
```

**@data-client/react/redux**

```typescript
import nock from 'nock';
import { useSuspense } from '@data-client/react';
import { makeRenderDataHook } from '@data-client/test';
import { DataProvider } from '@data-client/react/redux';
import { ArticleResource } from '../resources/Article';

describe('useSuspense()', () => {
  let renderDataHook: ReturnType<typeof makeRenderDataHook>;

  beforeEach(() => {
    nock(/.*/)
      .persist()
      .defaultReplyHeaders({
        'Access-Control-Allow-Origin': '*',
        'Content-Type': 'application/json',
      })
      .options(/.*/)
      .reply(200)
      .get(`/article/0`)
      .reply(403, {});
    renderDataHook = makeRenderDataHook(DataProvider);
  });

  afterEach(() => {
    nock.cleanAll();
  });

  it('should throw errors on bad network', async () => {
    const { result, waitFor } = renderDataHook(() => {
      return useSuspense(ArticleResource.get, {
        title: '0',
      });
    });
    expect(result.current).toBeUndefined();
    await waitFor(() => expect(result.current).toBeDefined());
    expect(result.error).toBeDefined();
    expect((result.error as any).status).toBe(403);
  });
});
```
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