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?

VitestでTypeError: window.matchMedia is not a functionがでた

1
Posted at

はじめに

前回の記事で、React Testing Libraryのwrapperを使用してproviderをまとめました。

この影響により、エラーが発生したのでその対処法をメモしました。

内容

TypeError: window.matchMedia is not a function

訳: window.matchMedia がないとのこと

なるほど。
テスト環境にwindow.matchMediaがないことでエラーなってました。

これ、providerに含まれるColorModeProviderwindow.matchMedia()を使用しているようです。

解決

セットアップファイルにモックを追加しました!

import "@testing-library/jest-dom/vitest";
import { vi } from "vitest";

// 簡易matchMedia
Object.defineProperty(window, "matchMedia", {
  writable: true,
  value: vi.fn().mockImplementation((query) => ({
    matches: false,
    media: query,
    onchange: null,
    addListener: vi.fn(),
    removeListener: vi.fn(),
    addEventListener: vi.fn(),
    removeEventListener: vi.fn(),
    dispatchEvent: vi.fn(),
  })),
});

まとめ

ChromeとかSafariでは動くけど、テスト環境ではブラウザを使わないからモックが必要なのですね!
勉強になりました。

参考

ありがとうございます!

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?