Skip to main content

Unit testing hooks

warning

Be careful with jest.mock 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 instead, or better, mockResolvedValue on your endpoints.

renderDataHook() renders a hook inside a DataProvider and a Suspense boundary. With React 18 or later, it wraps @testing-library/react's renderHook() in a DOM environment, or @testing-library/react-native's on React Native. Otherwise it uses @testing-library/react-hooks.

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:

npm install --save-dev whatwg-fetch
Run in your terminal

Jest​

// jest.config.js
module.exports = {
// other things
setupFiles: ['./testSetup.js'],
};
// testSetup.js
require('whatwg-fetch');

Example​

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