[note] React Hook Testing Library
此套件已棄用
@testing-library/react-hooks 已棄用。自 @testing-library/react v13.1.0 起,renderHook 已直接內建於 @testing-library/react 中,不再需要安裝獨立套件。請改用 import { renderHook, act } from '@testing-library/react'。此外,waitForNextUpdate 和 waitForValueToChange 已被移除,請改用 waitFor。
react-hooks-testing-library @ testing/library
React Hooks Testing Library 主要提供三個方法:renderHook, act 和 cleanup。
什麼時候該用此 library
根據官網的描述,使用此 library 前需要留意:
不要使用此 library 的時機
- 你的 Hook 只專門給某個對應的 component 使用時(通常 hook 檔案就直接放在 component 旁邊)
- 你的 Hook 非常容易測試,因此只需要直接針對元件進行測試即可
使用此 library 的時機
- 你正在寫一個函式庫,且裏面的 Hooks 並不是只在某個對應的元件中被使用
- 你的 Hook 非常複雜,以至於它沒有辦法單純靠測試元件就測到所有 hook 的功能
renderHook
透過 result.current 可以取得最新的資料狀態:
import { renderHook } from "@testing-library/react-hooks";
const renderHookResult = renderHook(callback, renderHookOptions);
// renderHookOptions
const renderHookOptions = {
initialProps,
wrapper,
};
// RenderHookResult
type RenderHookResult = {
// RenderResult
result: {
readonly all: Array<TValue | Error>;
readonly current: TValue;
readonly error?: Error;
}
// Renderer
render: (props?: TProps) => void;
rerender: (props?: TProps) => void;
unmount: () => void; // 用來觸發 useEffect 的 cleanup 函式
act: Act;
// AsyncUtils
waitFor: [Function: waitFor];
waitForNextUpdate: [Function: waitForNextUpdate];
waitForValueToChange: [Function: waitForValueToChange];
} ;