以互動方式測試函式

Cloud Functions 殼層提供互動式殼層,以使用測試資料叫用函式。殼層支援所有觸發條件類型。

設定管理員憑證 (選用)

如果想讓函式測試透過 Firebase Admin SDK 與 Google API 或其他 Firebase API 互動,您可能需要設定管理員憑證。

  • Cloud Firestore 和即時資料庫觸發條件已有足夠的憑證,因此不需要進行額外設定。
  • 所有其他 API (包括 Firebase API (例如 Authentication、FCM) 或 Cloud Translation 或 Cloud Speech 等 Google API,都必須完成本節所述的設定步驟。無論您使用的是 Cloud Functions 殼層還是 firebase emulators:start,都適用此規定。

如要為模擬函式設定管理員憑證,請按照下列指示操作:

  1. 開啟 Google Cloud 控制台的「Service Accounts」(服務帳戶) 窗格
  2. 確認已選取 [App Engine default service account] (App Engine 預設服務帳戶),並使用右側的選項選單選取 [Create key] (建立金鑰)
  3. 系統提示時,請在金鑰類型中選取「JSON」,然後按一下「建立」
  4. 將您的 Google 預設憑證設定為指向已下載的金鑰:

    Unix

    export GOOGLE_APPLICATION_CREDENTIALS="path/to/key.json"
    firebase functions:shell
    

    Windows

    set GOOGLE_APPLICATION_CREDENTIALS=path\to\key.json
    firebase functions:shell
    

完成這些步驟後,函式測試就能使用 Admin SDK 存取 Firebase 和 Google API。舉例來說,測試驗證觸發條件時,模擬函式可能會呼叫 admin.auth().getUserByEmail(email)

使用 Cloud Functions 殼層提供函式

Cloud Functions 殼層使用互動式殼層模擬所有類型的函式觸發條件,以使用測試資料叫用函式。可用的選項因函式類型而異,但基本用法格式如下:

myFunctionName(data, options)

即時資料庫、Cloud Firestore 和 PubSub 觸發條件都需要 data 參數,至於所有其他函式類型則為選用參數。此外,選用的 options 參數僅適用於即時資料庫和 Cloud Firestore 函式。

或者,您也可以將檔案儲存為變數,並使用該檔案叫用函式,藉此從本機檔案載入測試資料:

var data = require('./path/to/testData.json');
myFunction(data);

安裝及設定 Cloud Functions 殼層

如要使用這項功能,firebase-tools 最低需求為 3.11.0 版,而 firebase-functions SDK 的最低版本需求為 0.6.2。如要更新這兩項,請在專案的 functions/ 目錄中執行下列指令:

npm install --save firebase-functions@latest
npm install -g firebase-tools

如果您使用的是自訂函式設定變數,請先執行指令,在本機環境中取得自訂設定 (在 functions 目錄中執行):

firebase functions:config:get > .runtimeconfig.json
# If using Windows PowerShell, replace the above with:
# firebase functions:config:get | ac .runtimeconfig.json

最後,使用下列指令執行殼層:

firebase functions:shell

叫用 HTTPS 函式

在殼層中叫用 HTTPS 函式時,用法與 request NPM 模組相同,但請將 request 替換成您要模擬的函式名稱。例如:

# invoke
myHttpsFunction()
myHttpsFunction.get()
myHttpsFunction.post()

# invoke at sub-path
myHttpsFunction('/path')
myHttpsFunction.get('/path')
myHttpsFunction.post('/path')

# send POST request with form data
myHttpsFunction.post('/path').form( {foo: 'bar' })

叫用 HTTPS 可呼叫函式

在本機叫用 HTTPS 可呼叫函式時,您需要提供適當的測試資料。

# invoke
myCallableFunction('test data')
myCallableFunction({'foo': 'bar'})

您可以視需要傳入 Firebase-Instance-ID-token 做為第二個參數。必須是字串。

# invoke with FCM registration token
myCallableFunction('test data', {instanceIdToken: 'sample token'})

目前無法模擬「context.auth」。

叫用即時資料庫函式

在本機執行即時資料庫函式時,您必須提供適當的測試資料。這通常是指為 onCreate 作業、onDelete 作業的舊/已移除資料,以及 onUpdateonWrite 函式提供新的測試資料:

# invoke onCreate function
myDatabaseFunction('new_data')

# invoke onDelete function
myDatabaseFunction('old_data')

# invoke onUpdate or onWrite function
myDatabaseFunction({before: 'old_data', after: 'new_data' })

除了 before/after 選項之外,殼層還提供 params 選項,可用於在路徑中模擬萬用字元:

# mock wildcards in path, for example: if the path was input/{group}/{id}
myDatabaseFunction('data', {params: {group: 'a', id: 123}})

根據預設,殼層就會以管理員 (服務帳戶) 權限執行即時資料庫函式。使用 auth 選項,將函式改為以特定使用者或未經驗證的使用者的身分執行:

# to mock unauthenticated user
myDatabaseFunction('data', {authMode: 'USER'})
# to mock end user
myDatabaseFunction('data', {auth: {uid: 'abcd'}})

叫用 Firestore 函式

在本機執行 Firestore 函式時,必須提供適當的測試資料。這通常是指為 onCreate 作業、onDelete 作業的舊/已移除資料,以及 onUpdateonWrite 函式提供新的測試資料。請注意,Firestore 資料必須是鍵/值組合;請參閱支援的資料類型一文。

# invoke onCreate function
myFirestoreFunction({foo: ‘new’})

# invoke onDelete function
myFirestoreFunction({foo: ‘old’})

# invoke onUpdate or onWrite function
myFirestoreFunction({before: {foo: ‘old’}, after: {foo: ‘new’} })

除了 data 物件的 before/after 欄位外,您也可以使用 options 物件的 params 欄位模擬文件名稱中的萬用字元:

# mock wildcards in document name, for example: if the name was input/{group}/{id}
myFirestoreFunction({foo: ‘new’}, {params: {group: 'a', id: 123}})

殼層一律會以管理員權限執行 Firestore 函式,這意味著它模擬建立/更新/刪除事件的方式,就像執行系統管理員使用者一樣。

叫用 Pub/Sub 函式

針對 PubSub 函式,請在 Buffer 執行個體中插入訊息酬載,然後新增選用的資料屬性,如下所示:

// invokes a function with the JSON message { hello: 'world' } and attributes { foo: 'bar' }
myPubsubFunction({data: new Buffer('{"hello":"world"}'), attributes: {foo: 'bar'}})

叫用 Analytics (分析) 函式

您可以在殼層中執行 myAnalyticsFunction(),以叫用沒有任何資料的 Analytics (分析) 函式。如要使用測試資料執行函式,建議您針對函式所需的特定事件資料欄位定義變數:

var data = {
  eventDim: [{
    // populates event.data.params
    params: {foo: {stringValue: 'bar'} },
    // Also valid:
    //   {intValue: '10'}, {floatValue: '1.0'}, {doubleValue: '1.0'}
    // populates event.data.name
    name: 'event_name',
    // populates event.data.logTime, specify in microseconds
    timestampMicros: Date.now() * 1000,
    // populates event.data.previousLogTime, specify in microseconds
    previousTimestampMicros: Date.now() * 1000,
    // populates event.data.reportingDate, specify in 'YYYYMMDD' format
    date: '20170930',
    // populates event.data.valueInUSD
    valueInUsd: 230
  }],
  userDim: userDim
};

myAnalyticsFunction(data);

叫用儲存空間與驗證函式

針對儲存空間和驗證函式,請使用您想在函式中查看的測試資料叫用本機函式。測試資料必須符合下列相對應的資料格式:

請僅指定程式碼依附的欄位,或者如果您只想執行函式,則不指定任何欄位。