2
2

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-testing-library]Element type is invalid: expected a string (for built-in components) or a class/function~ というエラーの解決法

Posted at

発生したエラー

Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.

原因

  • Appコンポーネントをnamedでexportしているにも関わらず、テストを実行するファイルではdefalutexportをしたときのimportの記述方法になってしまっている為です。

エラーが発生する原因になっている箇所

componenteSample.spec.jsx
import App from "../App";
import React from "react";
import '@testing-library/jest-dom'
import { render, screen, fireEvent, waitFor } from "@testing-library/react";

describe("Title Test",() => {
  it("タイトルが学習記録であること", async () => {
    // testId(title)を指定して取得
        render(<App />);
        const title = await screen.findByTestId("title");
        expect(title).toHaveTextContent("学習記録");
         });
});

App.jsx
export const App = () => {
//中身は省略します
;

main.jsx
import { App } from './App';

解決方法

Appのimportをnamed形式に変更しました。

componenteSample.spec.jsx
import { App } from "../App";
import React from "react";
import '@testing-library/jest-dom'
import { render, screen, fireEvent, waitFor } from "@testing-library/react";

describe("Title Test",() => {
  it("タイトルが学習記録であること", async () => {
    // testId(title)を指定して取得
        render(<App />);
        const title = await screen.findByTestId("title");
        expect(title).toHaveTextContent("学習記録");
         });
});

さいごに

問題が発生したファイルだけではなく今やっていることに関連したファイルもエラー調査の際には見る必要があることを今回のエラーで実感しました。

2
2
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
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?