import { renderHook, act } from "@testing-library/react";
test("increments", () => {
const { result } = renderHook(() => useCounter(5));
act(() => result.current.increment());
expect(result.current.count).toBe(6);
});
Use renderHook from @testing-library/react. The separate @testing-library/react-hooks package is deprecated.
How it works:
- It renders a tiny test component that calls your hook.
- It returns
result.result.currentis the hook's latest return value. - Call state-changing functions inside
act, then readresult.currentagain. - Use
rerender(newProps)to test how the hook reacts to new arguments. - Use the
wrapperoption to supply providers.
renderHook fits reusable hooks with real logic, like useDebounce, usePagination or a hook in a shared library.
If only one component uses a hook, testing that component is usually better. It covers the hook through real behaviour. And your tests don't depend on how the code is split internally.
- Use
renderHookfrom@testing-library/react. result.currentholds the hook's latest return value.- Wrap updates in
act, and usererenderfor new props. - Use the
wrapperoption to supply providers. - Test through a component when the hook is an internal detail of it.
Read more