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のテスト環境にjest-domのmatcherを併用するための各種設定

1
Last updated at Posted at 2026-03-13

はじめに

Reactを使ったWebアプリケーションを開発している。

やりたいこと

テストにvitestとreact-testing-libraryを使用しているが、jest-domのtoBeInTheDocument()によるアサーションも使いたい。
セットアップの手順が色々面倒だったため、備忘のためここに記す。

手順

① npmで以下ライブラリをインストールする。

npm i --save-dev @testing-library/dom @testing-library/jest-dom @testing-library/react jsdom

② tsconfig.app.jsonファイルの設定で、compilerOptions.typesの配列に"@testing-library/jest-dom"を加える。

{
  "compilerOptions": {
    ...
    "types": ["vite/client","@testing-library/jest-dom"],
    ...

    }
  },
}

③ ルートディレクトリにvitest-config.tsを作成し、以下のように記載する。

import { defineConfig } from 'vitest/config';

export default defineConfig({
  test: {
    globals: true, 
    environment: 'jsdom', 
    setupFiles: './vitest-setup.ts', 
  },
});

④ルートディレクトリにvitest-setup.tsを作成し、以下のように記載する。

import '@testing-library/jest-dom/vitest';
import { vi } from 'vitest';
Object.defineProperty(window, 'matchMedia', {
  writable: true,
  value: vi.fn().mockImplementation(query => ({
    matches: false,
    media: query,
    onchange: null,
    addListener: vi.fn(), // deprecated
    removeListener: vi.fn(), // deprecated
    addEventListener: vi.fn(),
    removeEventListener: vi.fn(),
    dispatchEvent: vi.fn(),
  })),
});
window.HTMLElement.prototype.scrollIntoView = function() {};

↑1行目でjest-domをインポートしており、2行目以下ではテストでエラーとなりうるコンポーネントをモックしている

⑤ appディレクトリ配下にテスト用のディレクトリを作成する。名前は__test__などでよい

⑥__test__ディレクトリにXXX.spec.tsxというファイル名でテストファイルを作成する。

import { (中略) } from "@testing-library/react";

import * as matchers from "@testing-library/jest-dom/matchers";
expect.extend(matchers);
...

↑下2行でjest-domのmatcherをインポートし、vitestを拡張している。

これで、vitestでjest-domのmatcherが使えるようになるはず。

JISOUのメンバー募集中!

プログラミングコーチングJISOUでは、新たなメンバーを募集しています。
日本一のアウトプットコミュニティでキャリアアップしませんか?
興味のある方は、ぜひホームページをのぞいてみてください!
▼▼▼

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?