Skip to main content

[note] React Hook Testing Library

react-hooks-testing-library @ testing/library

React Hooks Testing Library 主要提供三個方法:renderHook, actcleanup

renderHook#

  • 透過 result.current 可以取得最新的資料狀態
import { renderHook } from "@testing-library/react-hooks";
const RenderHookResult = renderHook(callback, RenderHookOptions);
// RenderHookOptions
{
initialProps,
wrapper,
}
// RenderHookResult Object
{
result: { current: [Getter], error: [Getter] },
rerender: [Function: rerender],
unmount: [Function: unmountHook], // 用來觸發 useEffect 的 cleanup 函式
wait: [Function: wait],
waitForNextUpdate: [Function: waitForNextUpdate],
waitForValueToChange: [Function: waitForValueToChange]
}

Example#

import { renderHook, act } from '@testing-library/react-hooks';
import useOpenTokReducer from './use-opentok-reducer';
test('addConnection and removeConnection', () => {
const { result } = renderHook(() => useOpenTokReducer());
// 透過 result.current 取得初始的資料狀態
const [initialState, actions] = result.current;
const { addConnection, removeConnection } = actions;
const initialConnections = initialState.connections;
// 檢測起始狀態
expect(initialConnections).toEqual([]);
// 執行某個方法
act(() => {
addConnection({
id: mockData.id,
connectionId: mockData.id,
});
});
// 透過 result.current 取得最新的資料狀態
const [stateAfterAddConnection] = result.current;
// 檢測變更後的狀態
expect(stateAfterAddConnection.connections.length).toBe(initialConnections.length + 1);
// 執行某個方法
act(() => {
removeConnection({
id: mockData.id,
connectionId: mockData.id,
});
});
// 透過 result.current 取得最新的資料狀態
const [stateAfterRemoveConnection] = result.current;
// 檢測變更後的狀態
expect(stateAfterRemoveConnection.connections.length).toBe(initialConnections.length);
});

針對透過陣列解構賦值的 Hook#

針對會回傳陣列的 Hooks,可以在 renderHook 的 callback 中回傳解構後的內容:

describe('useOpenClose', () => {
// 在 renderHook 的 callback 中透過解構賦值來重新定義想要的結構
const { result } = renderHook(() => {
const [isOpen, actions] = useOpenClose();
return { isOpen, ...actions };
});
test('Should have initial value of false', () => {
console.log(result.current.isOpen);
});
test('Should update value to true', () => {
act(() => result.current.open());
console.log(result.current.isOpen);
});
});

act() doesn't seem to be updating state @ github issue

Last updated on