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?

Jest実行時に TextEncoder is not defined のエラーが発生したときの対処法

Last updated at Posted at 2025-03-16

はじめに

Jest でテストを実行した際に TextEncoder is not defined というエラーが発生しました。本記事では、エラーの原因とその解決方法についてまとめます。

エラー内容

npm run test を実行した際に、以下のエラーが発生しました。


FAIL src/__tests__/App.test.tsx
  ● Test suite failed to run

    🔴ReferenceError: TextEncoder is not defined

    > 1 | import { BrowserRouter, NavLink, Outlet, Route, Routes } from 'react-router';
        | ^
      2 | import './App.css';
      3 | import { Home } from './Home';
      4 | import { Hoge } from './Hoge';

      at Object.<anonymous> (node_modules/react-router/dist/development/index.js:8913:15)
      at Object.<anonymous> (src/App.tsx:1:1)
      at Object.<anonymous> (src/__tests__/App.test.tsx:2:1)

TextEncoderとは

TextEncoder は、文字列を UTF-8 のバイナリデータに変換するための Web API 。
TextEncoder を使うと、文字列をエンコードしてバイナリとして扱うことができます。

エラーの原因

Jest のデフォルトのテスト環境である jsdom には、TextEncoder / TextDecoder の実装が含まれていません。
そのため、TextEncoder を使用しているライブラリ(例えば、react-router など)をインポートすると、テスト実行時に TextEncoder is not defined というエラーが発生します。

よって、Jest の実行環境 jsdom では TextEncoder が提供されていないため、
テスト環境で TextEncoder を定義してあげる必要があります。

解決方法

1. jest-fixed-jsdom をインストール

プロジェクトのルートディレクトリで、以下のコマンドをターミナルで実行する。

npm i jest-fixed-jsdom

2. jest.config.ts にテスト環境を指定

Jest の設定ファイルに以下を追記。

module.exports = {
  testEnvironment: 'jest-fixed-jsdom',
}

これでエラーが解消されました

おわりに

これは回避策の1つであるらしく、現在は Vitest というフレームワークを使用することを推奨しているらしい。
Vitest はデフォルトで TextEncoder をサポートしておりこの問題に直面することはないそう。

参考

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?