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?

More than 1 year has passed since last update.

reactとtesting-libraryで単体テスト実行時のみ"Module 'useNavigate() may be used only in the context of a <Router> component."とエラーが出る

Posted at

概要

"Module '"react-router-dom"' has no exported member 'useHistory'"というエラーがテスト実行時のみ永遠に出て、1日以上苦しんだので同じく苦しんでいる人がいれば救いたいと思います。

今考えると状況整理がちゃんとできていればすぐ解決できたんじゃないかと思います><

環境

  • react-router-dom@6.10.0(当時のlatest)
  • react@18.2.0

結論

急いでいる人のために一旦結論だけ書いちゃいます!

下記のようにしてテストファイルのコンポーネントレンダリング時にコンポーネントでラップしないといけなかった。。。

render(<Router><AddMembers /></Router>);

全然出てこなかった

useNavigate() may be used only in the context of a component.でググる

エラー文でググると、大抵ルートコンポーネントで全部のコンポーネントをRouterでラップするようにしようという記事が大量に出てきた。

いやもうそれはとうにしてるんじゃ!!!

バージョンの問題

react-router-domがv18系から色々と変更があったようで、それも混乱の原因の一つだった。
関連するところで言うと、

  • 元々はuseHistory()を使ってナビゲーションをおこなっていたが、v18からはuseNavigateを使うようになった
  • useHistoryはpushを利用しなければならなかったが、不要になった
    など

なので、まず本記事を読んでいる方はバージョンとあった書き方をしている公式を絶対に確認すること

解決法

ひっっっったすらChat-GPT(GPT4)に聞きまくった。

  1. 該当ファイルを丸々コピペ→問題ないと言われる
  2. 関連するファイルを全てコピペ→問題ないと言われる
    「オワタ。。。あ、そういえばこれテスト時だけエラーなの念の為伝えておこっと(笑)」
    ワイ) "Btw I get the error on the console only when running unit test using testing-library. Does it matter??"
    GPT4先生) "It's possible that the issue you're experiencing is related to how your tests are set up. When using testing-library for testing components that use React Router, it's important to wrap the component being tested with a component in the test itself."
    →「まさにそれや。たわけ」
render(
    <Router>
      <Content setOpen={setOpen} setAlertLabel={setAlertLabel} />
    </Router>
  );

終わりに

やっぱりGPTさんはおま環の質問でも情報を与え続けることで状況を把握して、かなり精度の高い回答をしてくれるので本当に助かってます。

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?