1
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?

React, Jest map関数で回転させる時のルート要素の記述方法

Last updated at Posted at 2025-02-09

問題

React側で、map関数で回転させる時のルート要素の記述方法に誤りがあり、
Jestでテストを実施する時、WarningやErrorが出ました。

テストケース

想定通り、画面にテスト太郎が表示されることを確認したい。

CardPage.test.tsx
  test("名前が表示されている", async () => {
    render(
      <ChakraProvider value={defaultSystem}>
        <MemoryRouter initialEntries={["/cards/sample_id"]}>
          <Routes>
            <Route path="/cards/:id" element={<Card />} />
          </Routes>
        </MemoryRouter>
      </ChakraProvider>
    );

    await waitFor(() => {
      const nameText = screen.getByText(/テスト太郎/i);
      expect(nameText).toBeInTheDocument();
    });
  });

テストを受ける、React側の正しいコード

Card.tsx
return (
<>
  {data.length > 0 ? (
    data.map((item, index) => (
// map関数の中のルート要素で、エラーが出ない書き方
      <Fragment key={index}>

~~中略~~
      </Fragment>
    ))

Reactの、map関数の中のルート要素パターン

(1)Warningが出る

<>
~~中略~~
</>
→Warning: Each child in a list should have a unique "key" prop.

(2)Errorになる

<React.Fragment key={index}>
~~中略~~
 </React.Fragment>
→Error: Uncaught [TypeError: Cannot read properties of undefined (reading 'Fragment')]

(3)通る

import React, { useEffect, useState, Fragment } from "react";
<Fragment key={index}>
~~中略~~
</Fragment>
→OK

おわりに

解決まで2時間くらいかかってしまいました。
GitHub CopilotやClaudeで質問しましたが、今回はClaudeの回答が良かったです。

1
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
1
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?