LoginSignup
0
2

More than 3 years have passed since last update.

【Node.js】Firebaseでエミュレーターを使ったjestのCIをGithub Actionsで

Last updated at Posted at 2021-03-08

もうエミュレーターでテストすればいいんじゃないか説。

package.json
  "scripts": {
    "jest": "jest",
    "test": "firebase emulators:exec --only functions,firestore \"npm run jest --exit\"",
  }

別のFirebaseプロジェクトを用意する必要もないし、sinonでFirebaseAdminのモックとかも作る必要ないから楽。

Github Actions

jobs:
  ci:
    runs-on: ${{ matrix.os }}

    strategy:
      matrix:
        os: [ubuntu-latest]
        node: [12]

    steps:
      - name: Checkout 🛎
        uses: actions/checkout@master

      - name: Setup node env 🏗
        uses: actions/setup-node@v2.1.2
        with:
          node-version: ${{ matrix.node }}

      - name: Cache node_modules 📦
        uses: actions/cache@v2
        with:
          path: ~/.npm
          key: ${{ runner.os }}-node-${{ hashFiles('**/package-lock.json') }}
          restore-keys: |
            ${{ runner.os }}-node-

      - name: Install dependencies 👨🏻‍💻
        run: |
          npm install -g firebase-tools
          npm ci

      - name: Firebase runtime config 🔥
        uses: w9jds/firebase-action@master
        with:
          args: functions:config:get > .runtimeconfig.json
        env:
          FIREBASE_TOKEN: ${{ secrets.FIREBASE_TOKEN }}
          PROJECT_ID: "default"

      - name: Run linter 👀
        run: |
          npm run lint
          npm run test

functions.config()を使ってる場合は、firebase-actionsを使って.runtimeconfig.jsonに吐き出す。
また、エミュレーターの起動はfirebase-actionsを使わないのでnpm install -g firebase-toolsを忘れずに。

Cloud Storageのテスト

FirebaseのStorageは現状エミュレーターのサポート外なので、initializeAppで認証情報を渡してテストする。同じプロジェクトでテストする場合、バケットをテスト用に変更すると楽。(デフォルトで用意されてるstagingのバケットなど)

storage.test.js
import * as admin from 'firebase-admin';
import { config } from 'firebase-functions';
admin.initializeApp({
  credential: admin.credential.cert({
    project_id: config().credential.project_id,
    client_email: config().credential.client_email,
    private_key: config().credential.private_key.replace(/\\n/g, '\n'),
  }),
  storageBucket: 'staging.<PROJECT_ID>.appspot.com', // test用に変更
});

秘密鍵をfunctions.config()から読み込む場合、\n\\nになって
Failed to parse private key: Error: Invalid PEM formatted message.
と、認証でコケるので改行に置換してあげる。

0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2