JestのWebブラウザーAPIでのテスト環境設定

develop/JavaScript
概要

JavaScriptの人気テストフレームワークJest | GNU social JP」で記した通り、Jestの環境を用意しました。実際に最初のテストコードを作成して、npm run testで実行したところ、エラーが発生しました。その対応を記します。Jest v29.5で確認しました。

エラーは以下でした。

 FAIL  js/misc-functions.test.js
  ● Test suite failed to run

The error below may be caused by using the wrong test environment, see https://jestjs.io/docs/configuration#testenvironment-string. Consider using the "jsdom" test environment. ReferenceError: window is not defined 887 | · · · · · · · · · */ 888 | > 889 | window.userArrayCache = new Object();

どうやら、Webブラウザーのwindowオブジェクトを参照できずにエラーになっています。

設定

エラーにあるように、jsdomというテスト環境を使うとよいらしいです。「Configuring Jest · Jest」に記載があります。

JestのtestEnvironmentプロパティーがデフォルトだと”node”になっており、Node.jsでのテスト環境になっていて、Webブラウザーのオブジェクトを使えなかったのが原因のようです。”jsdom”にすればWebブラウザーでのテスト環境になるようです。

Jestの設定はjest.config.jsonとpackage.jsonに指定する2種類の方法があります。今回はpackage.jsonに以下の項目を追加して対応します。

{
"jest": {
"testEnvironment": "jsdom"
}
}
設置

追加してnpm run testを再実行すると、今度は以下の別のエラーが表示されました。

● Validation Error:

  Test environment jest-environment-jsdom cannot be found. Make sure the testEnvironment configuration option points to an existing node module.

  Configuration Documentation:
  https://jestjs.io/docs/configuration


As of Jest 28 "jest-environment-jsdom" is no longer shipped by default, make sure to install it separately.

jsdomはJest 28からデフォルトで同梱されなくなったらしいです。

From v27 to v28 · Jest」にあるとおり、以下のコマンドでjsdomを追加インストールします。

npm install -D jest-environment-jsdom

最終的に以下のpackage.jsonになっています。

{
  "type": "module",
  "jest": {
    "testEnvironment": "jsdom"
  },
  "scripts": {
    "test": "NODE_OPTIONS='--experimental-vm-modules --no-warnings' jest"
  },
  "devDependencies": {
    "jest": "^29.5.0",
    "jest-environment-jsdom": "^29.5.0"
  }
}

これでnpm run testを実行できました。

結論

JestのWebブラウザーAPIでのテスト環境設定でした。

元々Node.jsに準拠したテストフレームワークになっており、デフォルト設定がNode.js前提になっており、行き詰まりポイントでした。

これも最初だけなので、ひとまず次回以降は同様の手順で対応します。

Comments

  1. This Article was mentioned on web.gnusocial.jp

Copied title and URL