1
1

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】Vue3 + TypeScript + Vite

Posted at

はじめに

Vite上にVue3とTypeScriptの環境を構築し、JestをインストールしようとJestの公式ドキュメントを読んだところ、最新のVueへのJestのインストール方法がなく(最新版は本を買うように促された)ため、Vueの公式ドキュメントを読んだところ、Vitestというテスト用のライブラリがあると知り、インストールを行ってみました。

参考資料

環境

  • Vue3
  • TypeScript
  • Vite

テスト内容

App.vue内にVueというテキストが表示されていることをテストする

設定

src/App.vue
<script setup lang="ts"></script>

<template>
  <div>
    <h1>Vite</h1>
  </div>
</template>

<style scoped></style>

インストール

基本的には参考資料を元にインストールを進める

// プロジェクトに Vitest を追加する
npm install -D vitest happy-dom @testing-library/vue
vite.config.ts
import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";

// https://vite.dev/config/
export default defineConfig({
  plugins: [vue()],
+  test: {
+    // jest ライクなグローバルテスト API を有効化
+    globals: true,
+    // happy-dom で DOM をシミュレーションします
+    // (peer dependency として happy-dom のインストールが必要です)
+    environment: "happy-dom",
  },
});
tsconfig.json
{
  "files": [],
  "references": [
    { "path": "./tsconfig.app.json" },
    { "path": "./tsconfig.node.json" }
  ],
+  "compilerOptions": {
+    "types": ["vitest/globals"]
+  }
}
src/__tests__/sample.test.ts
// テストコードの記述
import { describe, expect, test } from "vitest";
import { render } from "@testing-library/vue";
import "@testing-library/jest-dom";
import AppVue from "../App.vue";

describe("Viteというテキストが表示されている", () => {
  test("Viteというテキストが表示されている", () => {
    const { getByText } = render(AppVue);
    expect(getByText("Vite")).toBeInTheDocument();
  });
});

エラー

上記の設定後、npm testを実行しましたが、

FAIL  src/__tests__/sample.test.ts > Viteというテキストが表示されている
Error: Invalid Chai property: toBeInTheDocument

このようなエラーが発生しました。

toBeInTheDocumentメソッドを使えるように、下記コマンドでjest-domをインストールします。

npm install -D @testing-library/jest-dom

sample.test.tsファイルにimport "@testing-library/jest-dom";を記述しjest-domをインポートします。

結果

再度npm testを実行すると、テストがPASSしました。

まとめ

ReactではJestをインストールし、テスト環境を設定しましたが、VueではVitestを使用しました。

使い方はJestと変わらないようなので、Vitestを使用してテストを書いていこうと思います。

1
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?