簡體   English   中英

單元測試firebase函數:如何存根firebase-admin sdk

[英]Unit testing firebase functions: how to stub firebase-admin sdk

在index.js中,我有以下內容

exports.write = functions.https.onRequest((req, res) => {
    admin.database()
        .ref(`xxx/yyy`)
        .push()
        .set({timestamp: admin.database.ServerValue.TIMESTAMP});
    res.status(200).end();
});

在我的test.js中,我將admin.database()存根如下:

const refStub = sinon.stub();
setStub = sinon.stub();
refStub.withArgs('xxx/yyy').returns({push: () => ({key: 'fakeKey', set: setStub})});
databaseStub = sinon.stub(admin, 'database').get(() => {
    return () => {
      return {ref: refStub};
    };
  });

當我運行我的測試時,我得到以下錯誤TypeError: Cannot read property 'TIMESTAMP' of undefined 如何修復此錯誤或將調用存根到admin.database.ServerValue.TIMESTAMP 謝謝。

在JavaScript中,函數可以具有屬性。

> function x() {}
undefined
> x
[Function: x]
> x.prop = 1
1
> x
{ [Function: x] prop: 1 }
> 

有了這些知識,存根admin.database非常簡單

var databaseStub = sinon.stub(admin, 'database').returns({ref: refStub});
//monkey patch database()'s property
admin.database.ServerValue = {TIMESTAMP: '1111'};

感謝Doug Stevenson在firebase slack頻道向我指出它。 謝謝道格!

admin.database.ServerValue.TIMESTAMP不是一個調用。 它是一個值永遠不會改變的對象 - 由服務器端的數據庫解釋的特殊值。 如果你打印它,它看起來像這樣:

{ '.sv': 'timestamp' }

因為它本質上是一個永不改變的常數值,所以不需要嘲笑它。

另外,我不清楚你是否正確使用它。 您應該將其指定為您寫入實時數據庫的對象的值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM