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】ReferenceError: document is not defined の原因と解決方法まとめ

1
Posted at

❗️ReferenceError: document is not defined

🔍 発生した問題

ReferenceError: document is not defined

yaml
Copy code

🔎 原因調査

  • テスト実行時に render() を使って DOM を触っていた。
  • しかし、Jest のデフォルト実行環境は node であり、documentwindow は存在しない。

📘 調査結果

Jest はデフォルトで Node.js 環境上で動作するため、ブラウザの DOM API が存在しない
このため、documentwindow にアクセスしようとするとエラーになる。


✅ 解決方法

jest.config.js に以下を追加する:

testEnvironment: "jsdom"

なぜその方法で解決できたのか

jsdom は Jest が利用できる 仮想ブラウザ環境です。
これにより、document や window、render() など DOM を必要とする関数もテスト内で正常に動作するようになります。

React コンポーネントのユニットテストでは jsdom を使うのが一般的です。

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?