0
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?

More than 1 year has passed since last update.

JestでLocalStorageのモックテストを行う際の問題解決

Posted at

課題

JavaScriptのテストフレームワークであるJestを使用してLocalStorageの処理のテストを実施しようとしたところ、下記のようなエラーが出てうまくいかない。

エラー1:
TypeError: jest.spyOn(...).mockImplementation is not a function
エラー2:
SecurityError: localStorage is not available for opaque origins

解決方法

  • jest-environment-jsdomをインストール、設定
  • LocalStorageのメソッドを直接spyするのではなく、Storage.prototypeをspyする

詳しい手順・実装内容

以下の実装により問題を解決しました:

まず、LocalStorageのメソッドを直接spyするのではなく、Storage.prototypeをspyする方法に切り替えました。
これにより、TypeError: jest.spyOn(...).mockImplementation is not a functionというエラーが解消しました。

jest.spyOn(Storage.prototype, "setItem").mockImplementation(jest.fn());
jest.spyOn(Storage.prototype, "getItem").mockImplementation((key) => {
  return mock_value;
});

expect(Storage.prototype.setItem).toHaveBeenCalledWith(
  "mock_key",
  "mock_value"
);

次に、"SecurityError: localStorage is not available for opaque origins"ですが、ググってみると設定ファイルにtestURLを指定すれば解決するという記事を見つけましたが、testURLを指定するとワーニングが出てうまくいきませんでした(Jestのバージョンは29.6.1)

Deprecation Warning:
Option "testURL" was replaced by passing the URL via "testEnvironmentOptions.url".
Please update your configuration.

色々調べた結果、jest-environment-jsdomを使うことで解決ができました。

まず、インストール

npm i jest-environment-jsdom

その後、jestの設定ファイルに下記を設定

module.exports = {
  testEnvironment: "jsdom",
};

これで先のテストコードと合わせて無事にテストを実施することができました。

0
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
0
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?