renderDataHook()
renderDataHook() 会为测试渲染一个使用 Reactive Data Client 的 hook。它会在
DataProvider 和 <Suspense/> 边界内渲染该 hook。在 React 18 或更高版本中,它在 DOM
环境下封装 @testing-library/react 的 renderHook(),在 React Native 上则封装 @testing-library/react-native 的版本。其他情况下它使用
@testing-library/react-hooks。它们都会给出下文所述的结果。
每次调用 renderDataHook() 都会创建新的 store 和新的 manager 实例,因此缓存和 manager 状态不会在多次调用之间延续。
类型
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>;
};
用法
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);
});
参数
callback
在 React 中运行的 hook。其返回值可以通过 result.current 获取
options.initialFixtures
如果测试需要缓存中预先存在数据,可以用它来预填充缓存。接收一个 fixture 数组
其效果等同于使用 mockInitialState() 初始化 <DataProvider />
options.resolverFixtures
这些 fixture 或 interceptor 用于响应任何新的请求。它最适合用来模拟变更这类命令式请求,也可以用来测试挂起状态或过渡。
其实现方式是添加 MockResolver 作为 wrapper。
options.getInitialInterceptorData
用于为所有 interceptor 初始化 this 属性的函数。
options.managers
返回要使用的 Manager。每次调用 renderDataHook() 都会调用它一次,因此每个测试都会得到新的实例。其结果会替换默认的 NetworkManager 和
SubscriptionManager。结果中必须包含一个 NetworkManager;当测试需要订阅时,再加上一个 SubscriptionManager。
要看到 fetch action,请把 Manager 放在 NetworkManager 之前,因为 NetworkManager 会处理它们而不会继续传递下去。
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
传给回调函数的初始值
options.wrapper
将一个 React 组件作为 wrapper 选项传入,它会被渲染在内部元素的外层
返回值
controller
用于 dispatch 命令式副作用的 Controller
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()
清理本次渲染的 manager。Reactive Data Client 的内部实现使用真实的定时器来避免竞态条件,因此当你模拟定时器时,这一点很重要。
清理会在每个测试结束后通过 afterEach hook 运行,与 @testing-library/react 类似。只有需要在测试中控制清理顺序时才需要自己调用它。例如,在从模拟定时器切换到真实定时器之前进行清理:
it('should handle polling', async () => {
jest.useFakeTimers();
const { result, cleanup } = renderDataHook(/* ... */);
// ... assertions ...
cleanup(); // must run while fake timers are still active
jest.useRealTimers();
});
allSettled()
返回一个 promise,在本次渲染的所有进行中的请求完成后 resolve。
renderDataHook.cleanup() 和 renderDataHook.allSettled() 只作用于最近一次渲染。请使用每次
renderDataHook() 调用返回的版本。
result
current(any)——callback函数的返回值error(Error)——如果callback函数在渲染期间抛出错误,则为所抛出的错误
waitFor
返回一个 Promise,当提供的回调执行时没有抛出异常、并返回真值或 undefined 时 resolve。可以放心地在回调中使用 renderDataHook 的结果来进行断言或检验值。
waitForNextUpdate
请改用 waitFor
返回一个 Promise,在 hook 下一次渲染时 resolve,通常发生在异步操作导致状态更新时。
rerender
(function([newProps]))——用于重新渲染测试组件(包括 callback 函数中调用的所有 hook)的函数。如果传入了 newProps,在之后的渲染中它们会替换传给 callback 函数的 initialProps。
unmount
(function())——用于卸载测试组件的函数,通常用来触发 useEffect hook 的清理副作用。
示例
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');
});