ST_FUNC開発日記

建築構造設計Excelアドイン開発の記録

Reactのテスト

サンプルプログラムをst-func用に書き換えていく。

まず、Home.tsxにタイトルと説明を記載。

import React from "react";

const Home: React.FC = () => {
  return (
    <div>
      <h1>st-func-web</h1>
      <p>建築構造設計に用いる簡単な計算をするアプリケーションです。</p>
    </div>
  );
};

export default Home;

App.test.tsxを見ながらHome.test.tsxを作成

import { render, screen } from "@testing-library/react";
import Home from "./Home";

test("renders home", () => {
  render(<Home />);
  const titleElement = screen.getByText(/st-func/i);
  expect(titleElement).toBeInTheDocument();
});
$ npm t

でテストは動いた。

なんか、今までのテストと少し動き方が違う気がするが、よしとする。

さて、次にApp.tsxのテストをしようとしているのだが全然うまくいかない。

test("has home page link", () => {
    render(<App />);
    const linkElement = screen.getByText(/home/i);

    expect(linkElement).toBeInTheDocument();
  });

というコードを書くと下記エラーが出る

TestingLibraryElementError: Unable to find an element with the text: /home/i. This could be because the text is broken up by multiple elements. In this case, you can provide a function for your text matcher to make your matcher more flexible.

検索やchatGPTで調べてみると、Routerを使っているのが問題みたいなのだが、うまく解決しない。

test("has home page link", () => {
    render(<App />, { wrapper: BrowserRouter });
    const linkElement = screen.getByText(/home/i);
    expect(linkElement).toBeInTheDocument();
  });

というのも試してみたが、

You cannot render a <Router> inside another <Router>. You should never have more than one in your app.

というエラーになる。

いろいろ試してみたが、うまくいかないので、いったんあきらめることにする・・・。

Routerでbasenameを指定しているのも複雑化させている気がする。

まあ、App.tsxはページ切り替えしか実装しなそうなので、特にテストしなくてもいいかな・・・?

Home.tsxの修正 · st-func/st-func-web@891c98f · GitHub