【问题标题】:Unit testing firebase functions: how to stub firebase-admin sdk单元测试firebase功能:如何存根firebase-admin sdk
【发布时间】:2017-12-22 09:58:00
【问题描述】:

在 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 的调用?谢谢。

【问题讨论】:

  • 我不明白你为什么要模拟set()时有sinon.stub(admin, 'database').get

标签: javascript unit-testing firebase firebase-realtime-database sinon


【解决方案1】:

在 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 频道上向我指出这一点。谢谢道格!

【讨论】:

    【解决方案2】:

    admin.database.ServerValue.TIMESTAMP 不是电话。它是一个值永远不会改变的对象——一个由服务器端的数据库解释的特殊值。如果你打印它,它看起来像这样:

    { '.sv': 'timestamp' }
    

    由于它本质上是一个永远不会改变的常量值,因此不需要对其进行模拟。

    另外,我不清楚您是否正确使用它。您应该将其分配为您写入实时数据库的对象的值。

    【讨论】:

    • 嗨,Doug,感谢您的回复。我已经编辑了我的帖子以使其更清晰。你介意再看一遍吗?谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-25
    • 2019-12-17
    • 2021-10-13
    • 1970-01-01
    • 1970-01-01
    • 2019-04-26
    相关资源
    最近更新 更多