DEV Community

Krzysztof Żuraw
Krzysztof Żuraw

Posted on • Originally published at krzysztofzuraw.com on

How you properly test your React hook methods

If you are using React Hooks testing library to test your hooks remember to wrap hooks methods in the act.

For example, if you try to run the test below:

import { renderHook } from "@testing-library/react-hooks";

test("test login", () => {
  const { result } = renderHook(() => useAuth());

  result.login();

  expect(result.user).toEqual({ token: "token", user: "Tom Smith" });
});
Enter fullscreen mode Exit fullscreen mode

You will get this error message:

Warning: An update to TestComponent inside a test was not wrapped in act(...).

When testing, code that causes React state updates should be wrapped into act(...):

act(() => {
  /* fire events that update state */
});
/* assert on the output */

This ensures that you're testing the behavior the user would see in the browser. Learn more at https://reactjs.org/link/wrap-tests-with-act
    at TestComponent ()
    at Suspense
    at ErrorBoundary ()
Enter fullscreen mode Exit fullscreen mode

To fix this you need to wrap the result.login call with the act:

-import { renderHook } from "@testing-library/react-hooks";
+import { renderHook, act } from "@testing-library/react-hooks";

test("test login", () => {
  const { result } = renderHook(() => useAuth());

- result.login();
+ act(() => {
+     result.login();
+ });

  expect(result.user).toEqual({ token: "token", user: "Tom Smith" });
});
Enter fullscreen mode Exit fullscreen mode

Top comments (0)