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】ReferenceError: TextEncoder is not definedエラーが発生する

Posted at

はじめに

テストを実行しようとした際に、表題のエラーが発生しました。

問題

● Test suite failed to run

    ReferenceError: TextEncoder is not defined

      1 | import { useEffect, useState } from "react";
    > 2 | import { useNavigate, useParams } from "react-router";
        | ^
      3 | import { getUserById } from "../utils/supabaseFunctions";
      4 | import { User } from "../domain/user";
      5 | import { Box, Button, Card, CardBody, Heading } from "@chakra-ui/react";

      at Object.<anonymous> (node_modules/react-router/dist/development/index.js:9351:15)
      at Object.<anonymous> (src/cards/UserCard.tsx:2:1)
      at Object.<anonymous> (src/__tests__/userCardComponent.spec.tsx:2:1)

原因

react-routerを導入している環境で、Jestを実行しようとしたため

テスト環境で react-router を使用する際に、TextEncoderというグローバルオブジェクトが定義されていないことが原因でした。
TextEncoder は通常ブラウザ環境で利用可能ですが、Node.js の Jest テスト環境ではデフォルトで定義されていません。

TextEncoderとは

MDNより引用

TextEncoder はコードポイントのストリームを入力として受け取り、 UTF-8 のバイトストリームを出力します。

文字列をUTF-8形式のバイトデータに変換するものと理解しました。

解決方法

jest.setup.tsTextEncoderTextDecoderのポリフィル(特定の機能が実行環境に存在しない場合、その機能を後から追加するためのコード)を追加する

:jest.setup.ts
import "@testing-library/jest-dom";
import { config } from "dotenv";
+ import util from "util";

config();

+// eslint-disable-next-line @typescript-eslint/no-require-imports
+global.TextEncoder = util.TextEncoder;
+// eslint-disable-next-line @typescript-eslint/no-require-imports
+global.TextDecoder = util.TextDecoder;

おわりに

今回、初めて使用するライブラリを使ったプロジェクトに対してテストすることに挑戦しています。
新たなエラーにたくさん出会いそうです。

参考

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?