前提
Next.jsとFirebase V9を使用しています。
JestとReact-testing-libraryを使ってテストを書き始めましたが、下記のエラーが表示されます。
The default Firebase app does not exist. Make sure you call initializeApp() before using any of the Firebase services.
実現したいこと
- エラーを解決してテストを実行したいです。
- セキュリティルールのテストではなく、コンポーネントやカスタムフックなどのロジックのテストを行ないたいです。
Firebaseのドキュメントでテストに言及するページを見つけたのですが、セキュリティルールに関するテストでした。
ルールのテストに関してはテスト用のライブラリがあり、そのライブラリとエミュレーターを使ったテスト方法が書かれています。
エミュレータ起動+テスト実行でルールのテストはできました。
- エミュレーターを使わないで済むテストの方法があれば知りたいです。
コンポーネントやロジックのテストをGithub Actionsで実行しようと考えています。
Github Actionsでエミュレーターは動かせるようですが、手間が多そうなのとルールのテストを実行するわけでは無いので、できることならエミュレーターは使いたくないです。
該当のソースコード
index.test.tsx
tsx
/** * @jest-environment jsdom */ import React from "react"; import { render } from "@testing-library/react"; import Home from "pages/index"; const mockArticles = [ { title: "foo", author: "bar" }, ]; describe("トップページ", () => { it("renders a heading", () => { const { getByText } = render(<Home articles={mockArticles} />); expect(getByText("トップ")).toBeInTheDocument(); }); });
jest.setup.ts
TypeScript
import "@testing-library/jest-dom/extend-expect"; import { getApps, initializeApp } from "firebase/app"; import UUID from "uuidjs"; const getUuid = () => UUID.generate(); const firebaseConfig = { apiKey: getUuid(), authDomain: getUuid(), projectId: getUuid(), storageBucket: getUuid(), messagingSenderId: getUuid(), appId: getUuid(), measurementId: getUuid(), }; beforeAll(async () => { const currentApps = getApps(); if (typeof window === "undefined" || currentApps.length !== 0) return; initializeApp(firebaseConfig); });
調べたこと
- FirebaseのIssueでエラー文で検索してみたのですが、該当するIssueが見つかりませんでした。
まだ回答がついていません
会員登録して回答してみよう