はじめに
ウェブフロントエンドアプリケーションを開発しているといくらユニットテストを書いていても、変更に不安を覚えるものがある。代表的なものがスタイルの変更かと思う。 このスタイルの変更にも安心感を与えてくれるテストの一つが Visual regression test と考え、今回は Cypress と reg-cli を使って試してみた。
アプリケーションの用意
Angular v16.0.x 系でアプリケーションの用意をする。これを試したときには v16.1.x で Cypress が動かない不具合があったのでこのバージョンにしている。 下記がリリースされれば、最新バージョンで問題ないと思う。
feat: support Angular 16.1 by leosvelperez · Pull Request #27030 · cypress-io/cypress · GitHub
Cypress の導入
自動テストを実行し、スクリーンショットを取るためのツールとして Cypress を導入する。 Cypress を選択したのにはあまり大きな意味はないが、公式ドキュメントに Angular 専用のページがあったりするため親和性が高いだろうと判断した。
導入は下記ページを参考におこなった。
Angular Component Testing | Cypress Documentation
- 下記コマンドで Cypress をインストール
npm i cypress -D
npx cypress open
を実行し GUI で設定ファイルを生成- Component Testing の方を選択し、設定を進めた
app.component.cy.ts を以下のように用意し、テストを実行してみる。
// app.component.cy.ts import { AppComponent } from "../src/app/app.component"; describe('app.component.cy.ts', () => { it('playground', () => { cy.mount(AppComponent) cy.screenshot(); }) })
テスト実行の際に、デフォルトだと E2E のテストを探してしまうので --component
オプションを付けて実行する。
npx cypress run --component
reg-cli の導入
続いて画像比較をするために reg-cli を導入する。
GitHub - reg-viz/reg-cli: 📷 Visual regression test tool.
- 下記コマンドで reg-cli をインストール
npm i -D reg-cli
README にあるように reg-cli /path/to/actual-dir /path/to/expected-dir /path/to/diff-dir -R ./report.html
で画像比較ができるので、これにあうように Cypress で撮ったスクリーンショットを配置する。
今回は以下のコマンドで画像比較できるようにそれぞれのディレクトリの役割を決めた。
npx reg-cli cypress/screenshots/actual/ cypress/screenshots/expected cypress/screenshots/diff -R cypress/reports/index.html -J cypress/reports/reg.json
結果の確認
cypress/reports/index.html に比較結果を出力するように指定したので、このファイルを開いてみる。 このような感じで actual と expected の比較ができている。
テストの準備は整ったので、実際にスタイルが変わったときに差分を検出するかを確認する。 まずは、以下のファイルに変更を加える。
❯ git diff diff --git a/src/app/app.component.html b/src/app/app.component.html index 2a0fbf1..b918365 100644 --- a/src/app/app.component.html +++ b/src/app/app.component.html @@ -135,7 +135,7 @@ } .card.highlight-card { - background-color: #1976d2; + background-color: #101011; color: white; font-weight: 600; border: none;
再度 Cypress でスクリーンショットを取り画像比較を実行する。
npx cypress run --component npx reg-cli cypress/screenshots/actual/ cypress/screenshots/expected cypress/screenshots/diff -R cypress/reports/index.html -J cypress/reports/reg.json
上記コマンドを実行後に cypress/reports/index.html を開くと差分が確認できた。
まとめ
今回は Cypress と reg-cli を使った Visual regression test を試してみた。期待した通りスタイルの変更を画像比較で検知できることまで確認できた。 Visual regression test をする際のツールの組み合わせは複数パターンあるが、まずは一つの組み合わせを試せたのでテストの幅が広がったと思う。
どのツールを使うのがよりベターか、どの単位で画像比較をしていくべきかなど Visual regression test についての調査は始まったばかりなので色々と試していきたい。