3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【RTL】テストは成功しているのにactで囲めと警告された

3
Last updated at Posted at 2026-11-06

はじめに

RTLでテストを行っていたらテストは成功しているのに、ターミナルに以下の警告が出ました。

An update to App 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://react.dev/link/wrap-tests-with-act

警告が出た状況と解消するまでをまとめます。

警告が出た状況

警告が出たのは以下のテストです。

App.test.jsx
test("h1タイトルの表示確認", async () => {
  render(<App />);

  const mainTitleElement = screen.getByRole("heading", {
    level: 1,
    name: "学習記録一覧",
  });

    expect(mainTitleElement).toBeInTheDocument();
});

getByRoleで取得している<h1>学習記録一覧</h1>はコンポーネントに直接書いています。そのためこのテスト自体はPASSします。

警告文内に出てくるactはRTLではなくReactのメソッドです。actで囲むとstateや副作用が完了した後に実行されます。

警告が出た原因

テストのアサーションをAppコンポーネントのstateの更新が完了する前に実行していたのが原因でした。

Reactは警告で「Appコンポーネントにまだ終わってないstateの更新があるのにテストして大丈夫?actで囲ってstateの更新が全部終わってからテストを実行した方がいいよ」と言ってくれてる訳です。

解決方法

Appコンポーネントの初回レンダリングの際に非同期でstateを更新している箇所があるためそこのstateが更新されるのを待ってからテストを実行します。

App.jsx
  useEffect(() => {
    const fetchTodos = async () => {
      try {
        const data = await getRecords(); // これ
        setRecords(data); // これも
      } catch (error) {
        console.error(error);
        setFetchErrorMessage("データを取得出来ませんでした。ページを更新して再度お試しください。");
      } finally {
        setLoading(false); // 最後のこれも
      }
    };

    fetchTodos();
  }, []);

ただ、今回は非同期でstateが更新されているため、actではなくwaitForを使います。

waitForはデフォルトで1秒(1000ms)待ち、その中で0.05秒(50ms)間隔で繰り返し実行を行います。この間に非同期処理の完了を待つことが出来ます。

警告ではactで囲ってと言われていますが、actはstateの更新と副作用を完了を待つメソッドのため、今回使っても警告が出たままになります。

finallyで実行しているローディング状態を管理するstateの更新の完了をwaitForで待ち、その後にアサーションを実行して解決しました。

App.test.jsx
test("h1タイトルの表示確認", async () => {
  render(<App />);

+ await waitFor(() => {
+   expect(screen.queryByText("データを取得中...")).not.toBeInTheDocument();
+ });

+  expect(
+    screen.getByRole("heading", { level: 1, name: "学習記録一覧" }),
+  ).toBeInTheDocument();
  });

ちなみにwaitForの中でアサーションしているのは以下のローディングコンポーネントのテキストです。

Loading.jsx
export const Loading = () => <div className="loading">データを取得中...</div>;

終わりに

テストではなく非同期処理の問題でした。非同期処理の理解に自信がないのでもう一度復習したいです。

3
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?