🐺

Firebase Emulator でテスト環境を整える

2025/02/08に公開

はじめに

Firebaseを利用しているプロジェクトが開発環境でも本物実行していたので
開発環境やテストにおいてFirebaseMockを利用して自動テストまで落とし込む話です。
※テストはe2e想定です。

FirebasaEmulatorとは

https://firebase.google.com/docs/emulator-suite?hl=ja

Firebase Local Emulator Suite は、Cloud Firestore、Realtime Database、Cloud Storage for Firebase、Authentication、Firebase Hosting、Cloud Functions(ベータ版)、Pub/Sub(ベータ版)、Firebase Extensions(ベータ版)を使用してアプリをローカルでビルドおよびテストするデベロッパー向けの高度なツールセットです。充実したユーザー インターフェースを備えており、アプリの本稼働やプロトタイピングにかかる時間を短縮できます。

CLI install

https://firebase.google.com/docs/cli?hl=ja#mac-linux-npm

Emulatorを起動するにはfirebase-toolsinstallします。

npm install -g firebase-tools

Emulatorを設定

すでにfirebaseの初期化が済んでいたいする場合もあるので
適宜状態に合わせてコマンドを実行します。

https://firebase.google.com/docs/emulator-suite/install_and_configure?hl=ja

実装

Emulatorと本物のきりかえに関する実装を記載していきます。
今回はenvによる切り替えで実装を進めました。

// initialize firebase
const app = !getApps().length ? initializeApp(firebaseConfig) : getApp()
const auth = getAuth(app)
const fireStore = getFirestore(app)

if (process.env.NODE_ENV === 'development') {
  // emulator settings
  if (!auth.emulatorConfig && !fireStore.emulatorConfig) {
    connectAuthEmulator(auth, 'http://localhost:9099') // firebase init emulators で設定したportを指定
    connectFirestoreEmulator(fireStore, 'localhost', 9100) // こちらも同様
  }
}

データの永続化

特にオプションを指定せず実行すると止める度にデータがなくなるため
下記オプションを付与して実行すると永続化されます。

firebase emulators:start --import data --export-on-exit

--import: import emulator data from a previous export (see emulators:export)
--export-on-exit: automatically export emulator data (emulators:export) when the emulators make a clean exit (SIGINT),when no dir is provided the location of --import [dir] is used

--importで前回のデータをインポートし、--export-on-exitEmulator終了時にエクスポートします。

ありがたいことにAuthenticationのデータも永続化できました。

https://firebase.google.com/docs/emulator-suite/install_and_configure?hl=ja

ローカルテスト

Firebase Emulatorを起動してe2eテストを実行していきます。
実行する際にEmulatorApplicationを同時に実行できるようにするとターミナル一つで済むため楽です。
個人的にはpackage.jsonscriptに登録して実行しています。

yarn dev & firebase emulators:start --import data --export-on-exit

正しく設定されていればEmulatorのデータを使用してテストが実行されます。

自動テスト(CI/CD)

自動テストを実行する環境はGitHubActionsを想定しています。

pipeline

最低限アプリケーションの実行と、firebase-toolsEmulatorが実行できれば
GitHubActions上でもテスト可能です。

    ...
    - name: Install Firebase CLI
    run: npm install -g firebase-tools

    - name: Run Application
    run: |
        yarn install
        yarn dev:with-firebase &
    env: # 今回は環境変数で切り替える想定
        NODE_ENV: development
        NEXT_PUBLIC_FIREBASE_API_KEY: xxxxxxxxx
        NEXT_PUBLIC_FIREBASE_PROJECT_ID: xxxxxxxxx
        NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET: xxxxxxxxx

    - name: Run E2E tests
    run: |
        pnpm install
        pnpm test
    ...

テストデータに関して

プロジェクトによっては、テスト専用のデータを登録するフローを別途検討する必要があると思いますが
このプロジェクトではデータの永続化で取得したデータを使用しています。

Discussion