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.

【Vue】Vitestで描画された文言をチェックしようとした時にハマったエラーの解決(document is not defined)

Last updated at Posted at 2023-10-14

背景

vueでwebサイトを制作する中で、ユニットテストを実施するためのテストコードをVitestで作成していた。
ユニットテストの内容としては、webサイト上に描画されたテキストに抜けがないか確認するための、文言チェックです。

実行環境

  • vue:3.3.4
  • vite:4.4.9
  • vitest:0.34.6
  • vue/test-utils:2.4.1

テストコード

以下のコードのように必要なライブラリ等をインポートし、
hogeという文言がinfo.vueファイルで描画されているかのテストをする内容です。

hoge.test.js
import { expect, describe, test } from 'vitest';
import { mount } from '@vue/test-utils';

// 外部フィアルのインポート
import Info from './src/components/info.vue';

describe(Info, () => {
    // ~
    test("描画文言テスト", () => {
        const wrapper = mount(Info);
        const allText = wrapper.text();
        expect(allText).toContain('hoge');
    });
    // ~
});

エラー内容

npm run testvitestコマンド実行時にmount部分で以下のエラーが発生。

ReferenceError: document is not defined
test("hoge test", () => {
    const wrapper = mount(Info);
                    ^
    const allText = wrapper.text();
    expect(allText).toContain('hoge');

エラーの原因

happy-domのインストールができておらず、実行環境をhappy-domに設定できていなかったため。

happy-domとは

仮想DOM環境を作成するためのライブラリ。
JSDOMという同様のライブラリもありますが、Happy DOMのほうが数倍処理が速い
jsdomライブラリより処理の速度が速いらしい。

解消方法

happy-domをインストールし、Viteプロジェクトでテスト環境を構成するための設定を変更。
具体的には、vite.config.jsファイル内のテストに使用する環境を happy-domとして設定。

1. happy-domのインストール

以下のコマンドを実行後にhappy-domをインストールするのかについてyes/noで聞かれます。
yを選択しhappy-domをインストールします。

npx vitest --dom

試してはないですが、以下のコマンドでもインストールできるのではないかと思ってます。

npm i -D happy-dom

インストールが完了すると、package.jsonにhappy-domが追加されている事が確認できます。

2. vite.config.jsファイルの修正

Viteプロジェクトのテスト環境としてhappy-domを使用するために、
以下のようにvite.config.jsファイルを修正します。

vite.config.js
export default defineConfig({
  // ~
  test: {
    environment: 'happy-dom',
  },
  // ~

3.実行

以下のコマンドでテストを実行しすると、エラーなくテストが通りました。

npm run test

◆ 補足

上記のコマンドを実行する上で、package.jsonには以下の記述がある事を想定しています。

package.json
{
  "scripts": {
   "test": "vitest"
  }
}
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?