Vueでテストを書く
Vueのアプリをテストファーストで書いてみます。
雛形のアプリを作る
新しいディレクトリにVueのアプリを作ります。
手元のXubuntu 24.01にはyarnパッケージとしてyarn 1.22.15が入っています。
$ mkdir clean-url
$ cd clean-url
$ yarn init
$ yarn add -D @vue/cli
$ yarn run vue create .
package.jsonを眺めると、yarn serveで開発用のサーバを起動できそうです。
{
"scripts": {
"serve": "vue-cli-service serve"
}
}
サーバが起動しました。念のためブラウザで閲覧できるのを確認します。
$ yarn serve
(中略)
App running at:
- Local: http://localhost:8080/
- Network: http://192.168.1.141:8080/
Note that the development build is not optimized.
To create a production build, run yarn build.
ユニットテストを書いて実行する
今回は、入力されたURLを加工するアプリを書いてみます。
まず、URLをパーズするヘルパ関数を書きます。
src/helpers.jsに、とりあえず最小の機能を持った下記の関数を定義します。
export function parseUrl(url) {
return URL.parse(url)
}
VueによるTestingガイドによると、テストフレームワークにはVitestが推奨のようです。インストールします。
$ yarn add -D vitest
Getting Startedガイドに従って、
package.jsonにtestスクリプトを追加します。
{
"scripts": {
"test": "vitest"
}
}
さらに、src/helpers.spec.jsにユニットテストを書きます。
import { describe, expect, test } from 'vitest'
import { parseUrl } from './helpers'
describe('parseUrl', () => {
test('parses a minimal URL', () => {
const parsed = parseUrl('https://example.com')
const expected = { host: 'example.com', protocol: 'https:' }
Object.entries(expected).forEach(([prop, goal]) => {
expect(parsed[prop]).toBe(goal)
})
})
})
ユニットテストを実行します。
$ yarn test
yarn run v1.22.15
$ vitest
DEV v4.0.18 /home/zunda/c/src/local/clean-url
✓ src/helpers.spec.js (1 test) 3ms
✓ parseUrl (1)
✓ parses a minimal URL 1ms
Test Files 1 passed (1)
Tests 1 passed (1)
Start at 15:11:03
Duration 190ms (transform 29ms, setup 0ms, import 44ms, tests 3ms, environment 0ms)
PASS Waiting for file changes...
press h to show help, press q to quit
成功しました。
© 2026 by zunda <https://zunda.ninja>,
licensed under CC BY 4.0.