Testes unitários de hooks
Tenha cuidado com o jest.mock em módulos do Reactive Data
Client. Um mock que remove exports causa erros difíceis de rastrear, como
TypeError: Class extends value undefined is not a function or null.
Use um mock parcial em vez disso ou, melhor ainda, mockResolvedValue nos seus endpoints.
O renderDataHook() renderiza um hook dentro de um DataProvider e de um boundary Suspense. Com React
18 ou posterior, ele envolve o renderHook() do @testing-library/react
em um ambiente DOM, ou o do @testing-library/react-native no React Native. Caso contrário, usa
@testing-library/react-hooks.
result.current é undefined até o hook retornar pela primeira vez. Se ele suspender de novo mais tarde, result.current mantém o último
valor. result.error guarda qualquer erro lançado pelo hook.
Cada chamada a renderDataHook() cria um novo store e novas instâncias de manager, então nenhum estado é mantido entre os testes.
Use initialFixtures para preparar o cache. A limpeza é executada automaticamente após cada teste.
Polyfill de fetch
O ambiente jsdom do Jest não tem um fetch global, mesmo no Node 18 e posterior. Adicione um polyfill:
- NPM
- Yarn
- pnpm
npm install --save-dev whatwg-fetch
yarn add --dev whatwg-fetch
pnpm add -D whatwg-fetch
Jest
// jest.config.js
module.exports = {
// other things
setupFiles: ['./testSetup.js'],
};
// testSetup.js
require('whatwg-fetch');
Exemplo
- @data-client/react
- @data-client/react/redux
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);
});
});
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);
});
});