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?

More than 1 year has passed since last update.

Jestでwindow.locationをモックしたい

Last updated at Posted at 2023-07-28

はじめに

Jestでテストを書いているときに地味に解決まで時間がかかってしまった箇所があったのでまとめます
案外ネットに記事が見当たらなかったり、ChatGPTも答えを教えてくれなかったりで困りました

問題

Jestでwindow.location.hrefをモックしたいと考えました
しかし、型エラーが発生して困りました

'delete' 演算子のオペランドはオプションである必要があります。
TypeError: Cannot set properties of undefined (setting 'href')Jest
var location: Location
TypeError: Cannot set properties of undefined (setting 'href')Jest
var location: Location
window not defined

など色々エラーが出て困りました

解決方法

まずはwindowを使うために以下のライブラリを入れました

$ npm i jest-environment-jsdom

そしてテスト環境で利用するように設定します

package.json
  "jest": {
    "testPathIgnorePatterns": [
      "<rootDir>/.types"
    ],
    "transform": {
      "^.+\\.(t|j)sx?$": "@swc/jest"
    },
    "testEnvironment": "jest-environment-jsdom" // 追加
  }

その後、以下のようにspy.Onを使ってモックすることでうまく行きました

test.spec.ts
describe("toNewsHeadlineUnitList", () => {

  let locationReplaceSpy: jest.SpyInstance;

  beforeAll(() => {
    locationReplaceSpy = jest.spyOn(window, 'location', 'get')
      .mockReturnValue({ href: '' } as any);
  });

  it("convert", () => {
    window.location.href = 'http://yourdamain.com';
    expect(window.location.href).toBe('http://yourdomain.com');
  });

  afterAll(() => {
    locationReplaceSpy.mockRestore();
  });
});

追記

beforeAllよりbeforeEachのほうが良いと思いました。

おわりに

案外SpyOnを利用する機会があるなぁと感じました
あとChatGPTも同じ解答を繰り返すということが多く、質問するの難しいなとなっています

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?