skip to content
Logo
Yurikago Blog
Table of Contents

@nuxt/test-utilsを利用したE2EテストのテストケースをTypeScriptで記述する方法を調べました。

検証環境

"devDependencies": {
"@babel/core": "^7.12.16",
"@babel/preset-env": "^7.12.16",
"@nuxt/test-utils": "^0.1.3",
"@types/jest": "^26.0.20",
"babel-jest": "^26.6.3",
"jest": "^26.6.3",
"playwright": "^1.8.1",
"ts-jest": "^26.5.1",
"typescript": "^4.1.5"
},
"dependencies": {
"nuxt": "^2.15.0"
}

検証リポジトリ: https://github.com/cuavv/sandbox-circleci-nuxt-test-utils

テストケースを作成する

ドキュメントのTesting in a browserを參考にテストケースを作成しました。テストの流れは以下です。

  1. setupTest でテスト対象のNuxtアプリケーション、ブラウザ(デフォルトだとChromium)を起動する。
  2. test でトップページに遷移し、CSSセレクタ(.title) から取得した要素のinnerTextが “fixture” と一致するかテストする。
test/e2e/index.spec.ts
import { setupTest, createPage } from '@nuxt/test-utils'
describe('Browser', () => {
setupTest({
browser: true,
})
test('test/fixture/pages/index.vue', async () => {
const page = await createPage('/')
const actual = await page.innerText('.title')
const expected = 'fixture'
expect(actual).toEqual(expected)
})
})

参考: https://test-utils.nuxtjs.org/api-reference/browser-testing

テスト対象のアプリケーションを作成

@nuxt/test-utilsはデフォルトだとtest/fixture/nuxt.config.jsを参照してNuxtアプリケーションを起動します。sandboxではtest/fixture以下にNuxtプロジェクトを作成しました。

テスト実行環境を作成

テストを実行する環境によって発生する問題を回避するためDockerコンテナを作成します。@nuxt/test-utilsの内部ではPlaywright (APIでブラウザを操作するNodeライブラリ) が動いており、Playwright公式によってDockerイメージが作成されています。今回はこのイメージを利用します。

infra/playwright/Dockerfile
FROM mcr.microsoft.com/playwright:bionic
RUN apt-get update
ENV PROJECT_ROOT=/var/www/playwright
WORKDIR $PROJECT_ROOT
COPY package.json .
COPY yarn.lock .
RUN yarn install

参考: https://playwright.dev/docs/docker

テストを実行

コンテナを作成後、コンテナに入って yarn test を実行します。

Terminal window
% docker-compose exec playwright bash
Terminal window
% yarn test

実行結果

Terminal window
% jest test/e2e
console.info
Using components loader to optimize imports
at node_modules/@nuxt/components/dist/index.js:167:15
console.info
Discovered Components: test/fixture/.nuxt/8sgi4095/components/readme.md
at node_modules/@nuxt/components/dist/index.js:230:13
PASS test/e2e/index.spec.ts (22.76 s)
Browser
setup nuxt (18427 ms)
test/fixture/pages/index.vue (955 ms)
Test Suites: 1 passed, 1 total
Tests: 2 passed, 2 total
Snapshots: 0 total
Time: 22.895 s
Ran all test suites matching /test\\e2e/i.
Done in 25.17s.

テストが無事にパスしました👏