[Advent Calendar 2021][Day18]E2Eテストを作る

undefined
はじめに
Advent Calendar 2021のDay18。 今回は、E2Eテストを作っていきます。
cypressをインストールする
E2Eテストでは定番のcypressを使います。
yarn add --dev cypress
参考
https://docs.cypress.io/guides/getting-started/installing-cypress
下記のように実行すると初回起動を検出してcypress
フォルダが作成されて以下にいくつかのファイルが自動的に作成されます。
yarn run cypress open
- cypress.json
{ "baseUrl": "http://localhost:3000"}
package.jsonに下記を足しておきます。
- package.json
"scripts" { "test": "jest", "e2e": "cypress run"}
cypress-firebaseをインストールする
今回はFirebase Authenticationを使っているので、Loginしないとテストできない機能があるので、こちらのPluginをインストールします。
yarn add -D cypress-firebase yarn add --dev firebase-admin@9
参考
https://github.com/prescottprue/cypress-firebase
上記の手順に従ってインストールします。
- cypress/support/commands.js
import firebase from "firebase/compat/app";import "firebase/compat/auth";import "firebase/compat/database";import "firebase/compat/firestore";import { attachCustomCommands } from "cypress-firebase";import { firebaseConfig } from '../../env.development'firebase.initializeApp(firebaseConfig);attachCustomCommands({ Cypress, cy, firebase });
- cypress/plugins/index.js
const admin = require("firebase-admin");const cypressFirebasePlugin = require("cypress-firebase").plugin;/** * @type {Cypress.PluginConfig} */// eslint-disable-next-line no-unused-varsmodule.exports = (on, config) => { const extendedConfig = cypressFirebasePlugin(on, config, admin); // Add other plugins/tasks such as code coverage here return extendedConfig;}
FirebaseAdminのserviceAccountが必要になるので、GCPコンソールから鍵をダウンロードして、serviceAccount.json
として保存しておきます。
また、事前にログインをしてUIDを取得ておきます。後にテスト実行時、UIDを環境変数に指定して実行すします。
E2Eテストを作る
トップページでカレンダーを作成するシナリオを書いてみます。
- cypress/integration/home_page_spec.js
describe('The Home Page', () => { before(() => { cy.login() }) it('create calendar', () => { cy.visit('/') cy.wait(1000) cy.get('.btn.btn-circle').click() cy.get('.input.input-primary').type('test calendar') cy.get('.btn.btn-primary').click() cy.wait(1000) }) })
E2Eテストを実行する
CYPRESS_TEST_UID=<uid> yarn e2e
テストを実施すると、cypress/videosの下に自動的に動画が作成されます。これは、とても便利です。エラーが起きたときにも役立ちますね。
まとめ
今回は、E2Eテストをつくりました。 次回は、改善について考えていきます。
