2
1

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環境エラー】ReferenceError: TextEncoder is not defined

Posted at

はじめに

React+TypeScriptの環境をViteで作成し、Jestをインストール後、
npm run testでテストする際にReferenceError: TextEncoder is not definedというエラーが発生しました。

当エラーの解決法についてご紹介します。

参考記事

解決方法

// jest.setup.tsに下記を追加
global.TextEncoder = require("util").TextEncoder;

// TextEncoderがすべてのテストでグローバルに使用できるようになる

原因

jest環境は、テスト用にブラウザのような環境をシミュレートするように設計されています。ただし、TextEncoderやTextDecoderなど、ブラウザ固有のオブジェクトがすべてデフォルトで含まれているわけではありません。そのため、これらのオブジェクトに依存するテストを実行するとエラーが発生する可能性があるようです。

TextEncoderは、文字列(UTF-8)をエンコードしてUint8Arrayとして扱うためのWeb APIです。

まとめ

Jest環境でテストしていて初めて遭遇したエラーでした。

これからどんどんテストを書いていってテスト実行時のエラーにも慣れていきたいです。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?