1. 始める前に
Cloud Firestore や Cloud Functions などのサーバーレス バックエンド ツールは非常に使いやすいですが、テストが難しい場合があります。Firebase Local Emulator Suite を使用すると、これらのサービスのローカル バージョンを開発マシンで実行できるため、アプリを迅速かつ安全に開発できます。
前提条件
- Visual Studio Code、Atom、Sublime Text などのシンプルなエディタ
- Node.js 10.0.0 以降(Node.js をインストールするには nvm を使用します。バージョンを確認するには
node --versionを実行します) - Java 7 以降(Java をインストールするには、こちらの手順を使用します。バージョンを確認するには、
java -versionを実行します)
演習内容
この Codelab では、複数の Firebase サービスを利用するシンプルなオンライン ショッピング アプリを実行してデバッグします。
- Cloud Firestore: グローバルにスケーラブルな、リアルタイム機能を備えたサーバーレスの NoSQL データベース。
- Cloud Functions: イベントや HTTP リクエストに応答して実行されるサーバーレス バックエンド コード。
- Firebase Authentication: 他の Firebase プロダクトと統合されるマネージド認証サービス。
- Firebase Hosting: ウェブアプリ向けの高速で安全なホスティング。
アプリを Emulator Suite に接続して、ローカル開発を可能にします。

さらに、次のことについても学びます。
- アプリを Emulator Suite に接続する方法と、さまざまなエミュレータがどのように接続されているか。
- Firebase セキュリティ ルールの仕組みと、ローカル エミュレータで Firestore セキュリティ ルールをテストする方法。
- Firestore イベントによってトリガーされる Firebase Functions の関数を作成する方法と、Emulator Suite に対して実行される統合テストを作成する方法。
2. 設定
ソースコードを取得する
この Codelab では、ほぼ完成しているバージョンの The Fire Store サンプルから始めます。そのため、最初に行う必要があるのは、ソースコードのクローンを作成することです。
$ git clone https://github.com/firebase/emulators-codelab.git
次に、codelab ディレクトリに移動します。この Codelab の残りの作業は、このディレクトリで行います。
$ cd emulators-codelab/codelab-initial-state
次に、コードを実行できるように依存関係をインストールします。インターネット接続の速度が遅い場合は、1 ~ 2 分かかることがあります。
# Move into the functions directory
$ cd functions
# Install dependencies
$ npm install
# Move back into the previous directory
$ cd ../
Firebase CLI を入手する
Emulator Suite は Firebase CLI(コマンドライン インターフェース)の一部です。Firebase CLI は、次のコマンドを使用してマシンにインストールできます。
$ npm install -g firebase-tools
次に、最新バージョンの CLI がインストールされていることを確認します。この Codelab はバージョン 9.0.0 以降で動作しますが、それ以降のバージョンにはより多くのバグの修正が含まれています。
$ firebase --version 9.6.0
Firebase プロジェクトに接続する
Firebase プロジェクトを作成する
- Google アカウントを使用して Firebase コンソールにログインします。
- ボタンをクリックして新しいプロジェクトを作成し、プロジェクト名(例:
Emulators Codelab)を入力します。
- [続行] をクリックします。
- Firebase の利用規約が表示されたら、内容を読み、同意して [続行] をクリックします。
- (省略可)Firebase コンソールで AI アシスタンス(「Gemini in Firebase」)を有効にします。
- この Codelab では Google アナリティクスは不要なため、Google アナリティクスのオプションをオフにします。
- [プロジェクトを作成] をクリックし、プロジェクトがプロビジョニングされるまで待ってから、[続行] をクリックします。
コードを Firebase プロジェクトに接続する
次に、このコードを Firebase プロジェクトに接続する必要があります。まず、次のコマンドを実行して Firebase CLI にログインします。
$ firebase login
次に、以下のコマンドを実行してプロジェクトのエイリアスを作成します。$YOUR_PROJECT_ID は、Firebase プロジェクトの ID に置き換えます。
$ firebase use $YOUR_PROJECT_ID
これでアプリを実行する準備が整いました。
3. エミュレータを実行する
このセクションでは、アプリをローカルで実行します。Emulator Suite を起動するタイミングです。
エミュレータを起動する
Codelab のソース ディレクトリ内から次のコマンドを実行して、エミュレータを起動します。
$ firebase emulators:start --import=./seed
以下のような出力が表示されます。
$ firebase emulators:start --import=./seed i emulators: Starting emulators: auth, functions, firestore, hosting ⚠ functions: The following emulators are not running, calls to these services from the Functions emulator will affect production: database, pubsub i firestore: Importing data from /Users/samstern/Projects/emulators-codelab/codelab-initial-state/seed/firestore_export/firestore_export.overall_export_metadata i firestore: Firestore Emulator logging to firestore-debug.log i hosting: Serving hosting files from: public ✔ hosting: Local server: http://127.0.0.1:5000 i ui: Emulator UI logging to ui-debug.log i functions: Watching "/Users/samstern/Projects/emulators-codelab/codelab-initial-state/functions" for Cloud Functions... ✔ functions[calculateCart]: firestore function initialized. ┌─────────────────────────────────────────────────────────────┐ │ ✔ All emulators ready! It is now safe to connect your app. │ │ i View Emulator UI at http://127.0.0.1:4000 │ └─────────────────────────────────────────────────────────────┘ ┌────────────────┬────────────────┬─────────────────────────────────┐ │ Emulator │ Host:Port │ View in Emulator UI │ ├────────────────┼────────────────┼─────────────────────────────────┤ │ Authentication │ 127.0.0.1:9099 │ http://127.0.0.1:4000/auth │ ├────────────────┼────────────────┼─────────────────────────────────┤ │ Functions │ 127.0.0.1:5001 │ http://127.0.0.1:4000/functions │ ├────────────────┼────────────────┼─────────────────────────────────┤ │ Firestore │ 127.0.0.1:8080 │ http://127.0.0.1:4000/firestore │ ├────────────────┼────────────────┼─────────────────────────────────┤ │ Hosting │ 127.0.0.1:5000 │ n/a │ └────────────────┴────────────────┴─────────────────────────────────┘ Emulator Hub running at 127.0.0.1:4400 Other reserved ports: 4500 Issues? Report them at https://github.com/firebase/firebase-tools/issues and attach the *-debug.log files.
「All emulators started」というメッセージが表示されたら、アプリを使用する準備は完了です。
ウェブアプリをエミュレータに接続する
ログの表から、Cloud Firestore エミュレータがポート 8080 でリッスンし、Authentication エミュレータがポート 9099 でリッスンしていることがわかります。
┌────────────────┬────────────────┬─────────────────────────────────┐ │ Emulator │ Host:Port │ View in Emulator UI │ ├────────────────┼────────────────┼─────────────────────────────────┤ │ Authentication │ 127.0.0.1:9099 │ http://127.0.0.1:4000/auth │ ├────────────────┼────────────────┼─────────────────────────────────┤ │ Functions │ 127.0.0.1:5001 │ http://127.0.0.1:4000/functions │ ├────────────────┼────────────────┼─────────────────────────────────┤ │ Firestore │ 127.0.0.1:8080 │ http://127.0.0.1:4000/firestore │ ├────────────────┼────────────────┼─────────────────────────────────┤ │ Hosting │ 127.0.0.1:5000 │ n/a │ └────────────────┴────────────────┴─────────────────────────────────┘
フロントエンド コードを本番環境ではなくエミュレータに接続しましょう。public/js/homepage.js ファイルを開き、onDocumentReady 関数を見つけます。このコードは、標準の Firestore インスタンスと Auth インスタンスにアクセスしています。
public/js/homepage.js
const auth = firebaseApp.auth();
const db = firebaseApp.firestore();
db オブジェクトと auth オブジェクトを更新して、ローカル エミュレータを指すようにしましょう。
public/js/homepage.js
const auth = firebaseApp.auth();
const db = firebaseApp.firestore();
// ADD THESE LINES
if (location.hostname === "127.0.0.1") {
console.log("127.0.0.1 detected!");
auth.useEmulator("http://127.0.0.1:9099");
db.useEmulator("127.0.0.1", 8080);
}
これで、アプリがローカルマシンで実行されている場合(Hosting エミュレータによって提供されている場合)、Firestore クライアントも本番環境のデータベースではなくローカル エミュレータを指すようになります。
EmulatorUI を開く
ウェブブラウザで http://127.0.0.1:4000/ に移動します。Emulator Suite UI が表示されます。

クリックすると、Firestore エミュレータの UI が表示されます。--import フラグを使用してインポートされたデータがあるため、items コレクションにはすでにデータが含まれています。

4. アプリを実行する
アプリを開く
ウェブブラウザで http://127.0.0.1:5000 に移動すると、マシンでローカルに実行されている The Fire Store が表示されます。

アプリを使用する
ホームページで商品を選択し、[カートに追加] をクリックします。残念ながら、次のエラーが発生します。

このバグを修正しましょう。すべてがエミュレータで実行されているため、実際のデータに影響を与えることを心配せずにテストできます。
5. アプリをデバッグする
バグを見つける
では、Chrome デベロッパー コンソールを見てみましょう。Control+Shift+J(Windows、Linux、Chrome OS)または Command+Option+J(Mac)を押して、コンソールにエラーを表示します。

addToCart メソッドでエラーが発生したようです。確認してみましょう。このメソッドで uid というものにアクセスしようとしているのはどこでしょうか。また、なぜ null になるのでしょうか。現時点では、public/js/homepage.js のメソッドは次のようになっています。
public/js/homepage.js
addToCart(id, itemData) {
console.log("addToCart", id, JSON.stringify(itemData));
return this.db
.collection("carts")
.doc(this.auth.currentUser.uid)
.collection("items")
.doc(id)
.set(itemData);
}
あった!アプリにログインしていません。Firebase Authentication のドキュメントによると、ログインしていない場合、auth.currentUser は null です。そのためのチェックを追加しましょう。
public/js/homepage.js
addToCart(id, itemData) {
// ADD THESE LINES
if (this.auth.currentUser === null) {
this.showError("You must be signed in!");
return;
}
// ...
}
アプリをテストする
ページを更新し、[カートに追加] をクリックします。今回は、次のようなエラーが表示されます。

しかし、上部のツールバーで [Sign In] をクリックしてから、もう一度 [Add to Cart] をクリックすると、カートが更新されます。
しかし、数字がまったく正しくないようです。

このバグはすぐに修正されます。まず、カートに商品を追加したときに実際に何が起こったのかを詳しく見てみましょう。
6. ローカル関数のトリガー
[Add to Cart] をクリックすると、複数のエミュレータが関与する一連のイベントが開始されます。カートに商品を追加すると、Firebase CLI ログに次のようなメッセージが表示されます。
i functions: Beginning execution of "calculateCart" i functions: Finished "calculateCart" in ~1s
これらのログと UI の更新を生成するために、4 つの重要なイベントが発生しました。

1)Firestore 書き込み - クライアント
Firestore コレクション /carts/{cartId}/items/{itemId}/ に新しいドキュメントが追加されます。このコードは、public/js/homepage.js 内の addToCart 関数で確認できます。
public/js/homepage.js
addToCart(id, itemData) {
// ...
console.log("addToCart", id, JSON.stringify(itemData));
return this.db
.collection("carts")
.doc(this.auth.currentUser.uid)
.collection("items")
.doc(id)
.set(itemData);
}
2) Cloud Functions の関数がトリガーされる
Cloud Functions の関数 calculateCart は、onWrite トリガーを使用して、カートアイテムに対して発生する書き込みイベント(作成、更新、削除)をリッスンします。これは functions/index.js で確認できます。
functions/index.js
exports.calculateCart = functions.firestore
.document("carts/{cartId}/items/{itemId}")
.onWrite(async (change, context) => {
try {
let totalPrice = 125.98;
let itemCount = 8;
const cartRef = db.collection("carts").doc(context.params.cartId);
await cartRef.update({
totalPrice,
itemCount
});
} catch(err) {
}
}
);
3) Firestore 書き込み - 管理者
calculateCart 関数は、カート内のすべての商品を読み取り、合計数量と合計金額を計算して、新しい合計で「cart」ドキュメントを更新します(上記の cartRef.update(...) を参照)。
4)Firestore の読み取り - クライアント
ウェブ フロントエンドは、カートの変更に関する更新情報を受け取るように登録されています。Cloud Functions の関数が新しい合計を書き込んで UI を更新すると、public/js/homepage.js に示すように、リアルタイムの更新が取得されます。
public/js/homepage.js
this.cartUnsub = cartRef.onSnapshot(cart => {
// The cart document was changed, update the UI
// ...
});
内容のまとめ
お疲れさまでした。3 つの異なる Firebase エミュレータを使用して、完全にローカルなテストを行う完全にローカルなアプリを設定しました。

それだけではありません。次のセクションでは、以下について説明します。
- Firebase エミュレータを使用する単体テストを作成する方法。
- Firebase エミュレータを使用してセキュリティ ルールをデバッグする方法。
7. アプリに合わせてセキュリティ ルールを作成する
このウェブアプリはデータの読み取りと書き込みを行いますが、これまでのところ、セキュリティについてはまったく考慮していません。Cloud Firestore では、「セキュリティ ルール」と呼ばれるシステムを使用して、データの読み取りと書き込みのアクセス権を持つユーザーを宣言します。Emulator Suite は、これらのルールのプロトタイプを作成するのに最適な方法です。
エディタで emulators-codelab/codelab-initial-state/firestore.rules ファイルを開きます。ルールには、次の 3 つの主要なセクションがあります。
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
// User's cart metadata
match /carts/{cartID} {
// TODO: Change these! Anyone can read or write.
allow read, write: if true;
}
// Items inside the user's cart
match /carts/{cartID}/items/{itemID} {
// TODO: Change these! Anyone can read or write.
allow read, write: if true;
}
// All items available in the store. Users can read
// items but never write them.
match /items/{itemID} {
allow read: if true;
}
}
}
現時点では、誰でもデータベースのデータの読み取りと書き込みができます。有効なオペレーションのみが通過し、機密情報が漏洩しないようにする必要があります。
この Codelab では、最小権限の原則に従って、すべてのドキュメントをロックし、すべてのユーザーが必要なアクセス権をすべて取得するまで、アクセス権を段階的に追加します。最初の 2 つのルールを更新して、条件を false に設定してアクセスを拒否しましょう。
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
// User's cart metadata
match /carts/{cartID} {
// UPDATE THIS LINE
allow read, write: if false;
}
// Items inside the user's cart
match /carts/{cartID}/items/{itemID} {
// UPDATE THIS LINE
allow read, write: if false;
}
// All items available in the store. Users can read
// items but never write them.
match /items/{itemID} {
allow read: if true;
}
}
}
8. エミュレータとテストを実行する
エミュレータを起動する
コマンドラインで、emulators-codelab/codelab-initial-state/ にいることを確認します。前の手順で起動したエミュレータがまだ実行されている可能性があります。実行されていない場合は、エミュレータを再度起動します。
$ firebase emulators:start --import=./seed
エミュレータが実行されたら、エミュレータに対してローカルでテストを実行できます。
テストを実行する
emulators-codelab/codelab-initial-state/ ディレクトリから新しいターミナル タブのコマンドラインで、次のコマンドを実行します。
まず、functions ディレクトリに移動します(この Codelab の残りの部分では、このディレクトリに留まります)。
$ cd functions
functions ディレクトリで mocha テストを実行し、出力の一番上までスクロールします。
# Run the tests
$ npm test
> functions@ test .../emulators-codelab/codelab-initial-state/functions
> mocha
shopping carts
1) can be created and updated by the cart owner
2) can be read only by the cart owner
shopping cart items
3) can be read only by the cart owner
4) can be added only by the cart owner
adding an item to the cart recalculates the cart total.
- should sum the cost of their items
0 passing (364ms)
1 pending
4 failing
現在、4 つのエラーがあります。ルールファイルを作成する際、合格するテストが増えることで、進捗状況を測定できます。
9. カートへの安全なアクセス
最初の 2 つの失敗は「ショッピング カート」のテストで、次のことをテストします。
- ユーザーは自分のカートのみを作成、更新できる
- ユーザーは自分のカートのみを読み取ることができる
functions/test.js
it('can be created and updated by the cart owner', async () => {
// Alice can create her own cart
await firebase.assertSucceeds(aliceDb.doc("carts/alicesCart").set({
ownerUID: "alice",
total: 0
}));
// Bob can't create Alice's cart
await firebase.assertFails(bobDb.doc("carts/alicesCart").set({
ownerUID: "alice",
total: 0
}));
// Alice can update her own cart with a new total
await firebase.assertSucceeds(aliceDb.doc("carts/alicesCart").update({
total: 1
}));
// Bob can't update Alice's cart with a new total
await firebase.assertFails(bobDb.doc("carts/alicesCart").update({
total: 1
}));
});
it("can be read only by the cart owner", async () => {
// Setup: Create Alice's cart as admin
await admin.doc("carts/alicesCart").set({
ownerUID: "alice",
total: 0
});
// Alice can read her own cart
await firebase.assertSucceeds(aliceDb.doc("carts/alicesCart").get());
// Bob can't read Alice's cart
await firebase.assertFails(bobDb.doc("carts/alicesCart").get());
});
これらのテストに合格するようにしましょう。エディタでセキュリティ ルール ファイル firestore.rules を開き、match /carts/{cartID} 内のステートメントを更新します。
firestore.rules
rules_version = '2';
service cloud.firestore {
// UPDATE THESE LINES
match /carts/{cartID} {
allow create: if request.auth.uid == request.resource.data.ownerUID;
allow read, update, delete: if request.auth.uid == resource.data.ownerUID;
}
// ...
}
}
これらのルールでは、カートのオーナーによる読み取りアクセスと書き込みアクセスのみが許可されるようになりました。
受信データとユーザーの認証を検証するには、すべてのルールのコンテキストで使用可能な 2 つのオブジェクトを使用します。
requestオブジェクトには、試行されているオペレーションに関するデータとメタデータが含まれています。- Firebase プロジェクトで Firebase Authentication を使用している場合、
request.authオブジェクトはリクエストを行っているユーザーを表します。
10. カートへのアクセスをテストする
Emulator Suite は、firestore.rules が保存されるたびにルールを自動的に更新します。エミュレータがルールを更新したことを確認するには、エミュレータを実行しているタブで Rules updated というメッセージを探します。

テストを再実行し、最初の 2 つのテストに合格することを確認します。
$ npm test
> functions@ test .../emulators-codelab/codelab-initial-state/functions
> mocha
shopping carts
✓ can be created and updated by the cart owner (195ms)
✓ can be read only by the cart owner (136ms)
shopping cart items
1) can be read only by the cart owner
2) can be added only by the cart owner
adding an item to the cart recalculates the cart total.
- should sum the cost of their items
2 passing (482ms)
1 pending
2 failing
よくできました!これで、ショッピング カートへのアクセスを保護できました。次の失敗したテストに進みましょう。
11. UI で [カートに追加] フローを確認する
現時点では、カートのオーナーはカートの読み取りと書き込みを行うことができますが、カート内の個々のアイテムの読み取りや書き込みはできません。これは、オーナーはカート ドキュメントにアクセスできますが、カートのアイテム サブコレクションにはアクセスできないためです。
これはユーザーにとって不具合のある状態です。
http://127.0.0.1:5000, で実行されているウェブ UI に戻り、カートに商品を追加してみます。items サブコレクションで作成されたドキュメントへのアクセス権をユーザーにまだ付与していないため、デバッグ コンソールに Permission Denied エラーが表示されます。
12. カート内の商品へのアクセスを許可する
次の 2 つのテストでは、ユーザーが自分のカートにのみアイテムを追加できること、自分のカートからのみアイテムを読み取れることを確認します。
it("can be read only by the cart owner", async () => {
// Alice can read items in her own cart
await firebase.assertSucceeds(aliceDb.doc("carts/alicesCart/items/milk").get());
// Bob can't read items in alice's cart
await firebase.assertFails(bobDb.doc("carts/alicesCart/items/milk").get())
});
it("can be added only by the cart owner", async () => {
// Alice can add an item to her own cart
await firebase.assertSucceeds(aliceDb.doc("carts/alicesCart/items/lemon").set({
name: "lemon",
price: 0.99
}));
// Bob can't add an item to alice's cart
await firebase.assertFails(bobDb.doc("carts/alicesCart/items/lemon").set({
name: "lemon",
price: 0.99
}));
});
そこで、現在のユーザーの UID がカート ドキュメントの ownerUID と同じ場合にアクセスを許可するルールを作成します。create, update, delete に異なるルールを指定する必要はないため、データを変更するすべてのリクエストに適用される write ルールを使用できます。
items サブコレクション内のドキュメントのルールを更新します。条件文の get は、Firestore から値を読み取っています。この例では、カート ドキュメントの ownerUID です。
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
// ...
// UPDATE THESE LINES
match /carts/{cartID}/items/{itemID} {
allow read, write: if get(/databases/$(database)/documents/carts/$(cartID)).data.ownerUID == request.auth.uid;
}
// ...
}
}
13. カートアイテムへのアクセスをテストする
これでテストを再実行できます。出力の一番上までスクロールして、合格したテストが増えていることを確認します。
$ npm test
> functions@ test .../emulators-codelab/codelab-initial-state/functions
> mocha
shopping carts
✓ can be created and updated by the cart owner (195ms)
✓ can be read only by the cart owner (136ms)
shopping cart items
✓ can be read only by the cart owner (111ms)
✓ can be added only by the cart owner
adding an item to the cart recalculates the cart total.
- should sum the cost of their items
4 passing (401ms)
1 pending
いいですね。これで、すべてのテストに合格しました。保留中のテストが 1 つありますが、これについては数ステップ後に説明します。
14. 「カートに追加」フローをもう一度確認する
ウェブ フロントエンド(http://127.0.0.1:5000)に戻り、カートに商品を追加します。これは、テストとルールがクライアントの求める機能と一致していることを確認するための重要なステップです。(前回 UI を試したとき、ユーザーはカートに商品を追加できなかったことを思い出してください)。

firestore.rules が保存されると、クライアントは自動的にルールを再読み込みします。カートに商品を追加してみましょう。
内容のまとめ
お疲れさまでした。アプリのセキュリティを強化しました。これは、アプリを製品版として準備するための重要なステップです。これが本番環境アプリであれば、これらのテストを継続的インテグレーション パイプラインに追加できます。これにより、他のユーザーがルールを変更した場合でも、ショッピング カートのデータにこれらのアクセス制御が適用されるという確信が得られます。

さらなる効果 -
このまま読み進めると、次のことがわかります。
- Firestore イベントによってトリガーされる関数の作成方法
- 複数のエミュレータで動作するテストを作成する方法
15. Cloud Functions のテストを設定する
ここまでは、ウェブアプリのフロントエンドと Firestore セキュリティ ルールに焦点を当ててきました。このアプリは Cloud Functions を使用してユーザーのカートを最新の状態に保つため、そのコードもテストする必要があります。
Emulator Suite を使用すると、Cloud Functions のテストが非常に簡単になります。Cloud Firestore やその他のサービスを使用する関数もテストできます。
エディタで emulators-codelab/codelab-initial-state/functions/test.js ファイルを開き、ファイルの最後のテストまでスクロールします。現時点では、保留中としてマークされています。
// REMOVE .skip FROM THIS LINE
describe.skip("adding an item to the cart recalculates the cart total. ", () => {
// ...
it("should sum the cost of their items", async () => {
...
});
});
テストを有効にするには、.skip を削除して次のようにします。
describe("adding an item to the cart recalculates the cart total. ", () => {
// ...
it("should sum the cost of their items", async () => {
...
});
});
次に、ファイルの先頭にある REAL_FIREBASE_PROJECT_ID 変数を見つけて、実際の Firebase プロジェクト ID に変更します。
// CHANGE THIS LINE
const REAL_FIREBASE_PROJECT_ID = "changeme";
プロジェクト ID を忘れた場合は、Firebase コンソールの [プロジェクトの設定] で Firebase プロジェクト ID を確認できます。

16. 機能テストを試す
このテストでは Cloud Firestore と Cloud Functions の間のインタラクションを検証するため、前の Codelab のテストよりも多くの設定が必要になります。このテストを詳しく見て、どのような結果が期待されるのかを把握しましょう。
カートを作成する
Cloud Functions は信頼できるサーバー環境で実行され、Admin SDK で使用されるサービス アカウント認証を使用できます。まず、initializeApp ではなく initializeAdminApp を使用してアプリを初期化します。次に、商品を追加するカートの DocumentReference を作成し、カートを初期化します。
it("should sum the cost of their items", async () => {
const db = firebase
.initializeAdminApp({ projectId: REAL_FIREBASE_PROJECT_ID })
.firestore();
// Setup: Initialize cart
const aliceCartRef = db.doc("carts/alice")
await aliceCartRef.set({ ownerUID: "alice", totalPrice: 0 });
...
});
関数をトリガーする
次に、関数をトリガーするために、カート ドキュメントの items サブコレクションにドキュメントを追加します。関数で行われる加算をテストするために、2 つの項目を追加します。
it("should sum the cost of their items", async () => {
const db = firebase
.initializeAdminApp({ projectId: REAL_FIREBASE_PROJECT_ID })
.firestore();
// Setup: Initialize cart
const aliceCartRef = db.doc("carts/alice")
await aliceCartRef.set({ ownerUID: "alice", totalPrice: 0 });
// Trigger calculateCart by adding items to the cart
const aliceItemsRef = aliceCartRef.collection("items");
await aliceItemsRef.doc("doc1").set({name: "nectarine", price: 2.99});
await aliceItemsRef.doc("doc2").set({ name: "grapefruit", price: 6.99 });
...
});
});
テストの期待値を設定する
onSnapshot() を使用して、カート ドキュメントの変更をリッスンするリスナーを登録します。onSnapshot() は、リスナーの登録を解除するために呼び出すことができる関数を返します。
このテストでは、合計金額が $9.98 になるように 2 つの商品を追加します。次に、カートに想定される itemCount と totalPrice があるかどうかを確認します。その場合、関数はその役割を果たしたことになります。
it("should sum the cost of their items", (done) => {
const db = firebase
.initializeAdminApp({ projectId: REAL_FIREBASE_PROJECT_ID })
.firestore();
// Setup: Initialize cart
const aliceCartRef = db.doc("carts/alice")
aliceCartRef.set({ ownerUID: "alice", totalPrice: 0 });
// Trigger calculateCart by adding items to the cart
const aliceItemsRef = aliceCartRef.collection("items");
aliceItemsRef.doc("doc1").set({name: "nectarine", price: 2.99});
aliceItemsRef.doc("doc2").set({ name: "grapefruit", price: 6.99 });
// Listen for every update to the cart. Every time an item is added to
// the cart's subcollection of items, the function updates `totalPrice`
// and `itemCount` attributes on the cart.
// Returns a function that can be called to unsubscribe the listener.
await new Promise((resolve) => {
const unsubscribe = aliceCartRef.onSnapshot(snap => {
// If the function worked, these will be cart's final attributes.
const expectedCount = 2;
const expectedTotal = 9.98;
// When the `itemCount`and `totalPrice` match the expectations for the
// two items added, the promise resolves, and the test passes.
if (snap.data().itemCount === expectedCount && snap.data().totalPrice == expectedTotal) {
// Call the function returned by `onSnapshot` to unsubscribe from updates
unsubscribe();
resolve();
};
});
});
});
});
17. テストを実行する
以前のテストでエミュレータが実行されている可能性があります。起動していない場合は、エミュレータを起動します。コマンドラインから次のコマンドを実行します。
$ firebase emulators:start --import=./seed
新しいターミナル タブを開き(エミュレータは実行したままにします)、functions ディレクトリに移動します。セキュリティ ルールのテストから、このタブが開いたままになっている可能性があります。
$ cd functions
単体テストを実行すると、合計 5 つのテストが表示されます。
$ npm test
> functions@ test .../emulators-codelab/codelab-initial-state/functions
> mocha
shopping cart creation
✓ can be created by the cart owner (82ms)
shopping cart reads, updates, and deletes
✓ cart can be read by the cart owner (42ms)
shopping cart items
✓ items can be read by the cart owner (40ms)
✓ items can be added by the cart owner
adding an item to the cart recalculates the cart total.
1) should sum the cost of their items
4 passing (2s)
1 failing
特定の失敗を確認すると、タイムアウト エラーのようです。これは、テストが関数の正しい更新を待機しているものの、更新が行われないためです。これで、テストを満たす関数を作成する準備が整いました。
18. 関数を作成する
このテストを修正するには、functions/index.js の関数を更新する必要があります。この関数の一部は記述されていますが、完全ではありません。現在の関数は次のようになっています。
// Recalculates the total cost of a cart; triggered when there's a change
// to any items in a cart.
exports.calculateCart = functions
.firestore.document("carts/{cartId}/items/{itemId}")
.onWrite(async (change, context) => {
console.log(`onWrite: ${change.after.ref.path}`);
if (!change.after.exists) {
// Ignore deletes
return;
}
let totalPrice = 125.98;
let itemCount = 8;
try {
const cartRef = db.collection("carts").doc(context.params.cartId);
await cartRef.update({
totalPrice,
itemCount
});
} catch(err) {
}
});
この関数は、カート参照を正しく設定していますが、totalPrice と itemCount の値を計算する代わりに、ハードコードされた値に更新しています。
items サブコレクション
新しい定数 itemsSnap を初期化して、items サブコレクションにします。次に、コレクション内のすべてのドキュメントを反復処理します。
// Recalculates the total cost of a cart; triggered when there's a change
// to any items in a cart.
exports.calculateCart = functions
.firestore.document("carts/{cartId}/items/{itemId}")
.onWrite(async (change, context) => {
console.log(`onWrite: ${change.after.ref.path}`);
if (!change.after.exists) {
// Ignore deletes
return;
}
try {
let totalPrice = 125.98;
let itemCount = 8;
const cartRef = db.collection("carts").doc(context.params.cartId);
// ADD LINES FROM HERE
const itemsSnap = await cartRef.collection("items").get();
itemsSnap.docs.forEach(item => {
const itemData = item.data();
})
// TO HERE
return cartRef.update({
totalPrice,
itemCount
});
} catch(err) {
}
});
totalPrice と itemCount を計算する
まず、totalPrice と itemCount の値をゼロに初期化します。
次に、反復処理ブロックにロジックを追加します。まず、商品に価格が設定されていることを確認します。数量が指定されていないアイテムについては、デフォルトで 1 に設定します。次に、数量を itemCount の累計に加算します。最後に、アイテムの価格に数量を掛けた値を totalPrice の累計に加算します。
// Recalculates the total cost of a cart; triggered when there's a change
// to any items in a cart.
exports.calculateCart = functions
.firestore.document("carts/{cartId}/items/{itemId}")
.onWrite(async (change, context) => {
console.log(`onWrite: ${change.after.ref.path}`);
if (!change.after.exists) {
// Ignore deletes
return;
}
try {
// CHANGE THESE LINES
let totalPrice = 0;
let itemCount = 0;
const cartRef = db.collection("carts").doc(context.params.cartId);
const itemsSnap = await cartRef.collection("items").get();
itemsSnap.docs.forEach(item => {
const itemData = item.data();
// ADD LINES FROM HERE
if (itemData.price) {
// If not specified, the quantity is 1
const quantity = itemData.quantity ? itemData.quantity : 1;
itemCount += quantity;
totalPrice += (itemData.price * quantity);
}
// TO HERE
})
await cartRef.update({
totalPrice,
itemCount
});
} catch(err) {
}
});
また、成功状態とエラー状態のデバッグに役立つロギングを追加することもできます。
// Recalculates the total cost of a cart; triggered when there's a change
// to any items in a cart.
exports.calculateCart = functions
.firestore.document("carts/{cartId}/items/{itemId}")
.onWrite(async (change, context) => {
console.log(`onWrite: ${change.after.ref.path}`);
if (!change.after.exists) {
// Ignore deletes
return;
}
let totalPrice = 0;
let itemCount = 0;
try {
const cartRef = db.collection("carts").doc(context.params.cartId);
const itemsSnap = await cartRef.collection("items").get();
itemsSnap.docs.forEach(item => {
const itemData = item.data();
if (itemData.price) {
// If not specified, the quantity is 1
const quantity = (itemData.quantity) ? itemData.quantity : 1;
itemCount += quantity;
totalPrice += (itemData.price * quantity);
}
});
await cartRef.update({
totalPrice,
itemCount
});
// OPTIONAL LOGGING HERE
console.log("Cart total successfully recalculated: ", totalPrice);
} catch(err) {
// OPTIONAL LOGGING HERE
console.warn("update error", err);
}
});
19. テストを再実行する
コマンドラインで、エミュレータがまだ実行されていることを確認し、テストを再実行します。エミュレータは関数の変更を自動的に取得するため、再起動する必要はありません。すべてのテストに合格したことがわかります。
$ npm test
> functions@ test .../emulators-codelab/codelab-initial-state/functions
> mocha
shopping cart creation
✓ can be created by the cart owner (306ms)
shopping cart reads, updates, and deletes
✓ cart can be read by the cart owner (59ms)
shopping cart items
✓ items can be read by the cart owner
✓ items can be added by the cart owner
adding an item to the cart recalculates the cart total.
✓ should sum the cost of their items (800ms)
5 passing (1s)
よくできました!
20. Storefront UI を使用して試す
最後のテストとして、ウェブアプリ(http://127.0.0.1:5000/)に戻り、カートに商品を追加します。

カートが正しい合計金額で更新されることを確認します。ではさっそく、
内容のまとめ
Cloud Functions for Firebase と Cloud Firestore の間の複雑なテストケースについて説明しました。テストに合格するように Cloud Functions の関数を作成しました。また、新しい機能が UI で動作していることも確認しました。これらはすべて、自分のマシンでエミュレータを実行してローカルで行いました。
また、ローカル エミュレータに対して実行されるウェブ クライアントを作成し、データを保護するためにセキュリティ ルールを調整し、ローカル エミュレータを使用してセキュリティ ルールをテストしました。
