以前Vitestについて軽く調べたが、実際に試してみる
こちらの記事を参考にさせていただく
上の記事ではReactだが、今回はVueで同じようなことをやってみる
テストするページはテンプレートから作ったままのこちらのページ
以下をインストールする
$ npm i -D @testing-library/react $ npm i -D @testing-library/jest-dom $ npm i -D happy-dom $ npm i -D @testing-library/user-event
vite.config.tsを編集する
/// <reference types="vitest" /> import { defineConfig } from 'vite' import vue from '@vitejs/plugin-vue' ... export default defineConfig({ ... test: { globals: true, environment: 'happy-dom', } })
まず、vite.config.tsに設定を書く場合は文頭に/// <reference types="vitest" />
が必要なため記載する
次に、test.globals
とtest.environment
を設定する
test.globals
は明示的にdescription, test, expect
のimportを書いたほうがよいと思ってfalse
のままがよかったが、なぜかimportしているのに未定義エラーになってしまうので仕方なくtrue
にした
test.environment
はnode
, 'js-dom', 'happy-dom'のいずれかが指定可能だが、記事通り'happy-dom'にしてみた
testファイルはつまづきポイントが多かった
import '@testing-library/jest-dom' import { describe, expect, test } from 'vitest' import App from './App.vue' import { render, screen, fireEvent } from '@testing-library/vue' import userEvent from '@testing-library/user-event' describe('Simple working test', () => { test('should render correctly', () => { const {container} = render(App) expect(container.firstChild).toMatchSnapshot() }) // extend-expectのmatcher[toBeInTheDocument] test('the title is visible', () => { render(App) expect(screen.getByText(/Hello Vue 3 \+ TypeScript \+ Vite/i)).toBeInTheDocument() }) // jest-extendedのmatcher[toBeEmptyDOMElement] test('should increment count on click', async() => { render(App) fireEvent.click(screen.getByRole('button')) expect(await screen.findByText(/count is: 1/i)) }) })
まずimport '@testing-library/jest-dom'
はimportしないと.toBeInTheDocument()
などの matcher が未定義になりエラーとなった
次に、ReactであればuserEvent.click(screen.getByRole('button'))
でイベントが発火するのだが、Vueだと発火しなかった
代わりにfireEvent.click(screen.getByRole('button'))
を使ってあげる
これはこちらが参考になった
testing-library/user-eventではVueが期待するchangeイベントを発火できない
とりあえずこれでテスト実行することができた