【问题标题】:How to stub external services in Firebase emulator?如何在 Firebase 模拟器中存根外部服务?
【发布时间】:2020-11-14 06:49:35
【问题描述】:

我有一个基于 slug 属性创建 DNS 记录的 firestore 触发器功能。我有一些单元测试,我在其中存根 @google-cloud/dns 模块,因此没有发出外部 HTTP 请求。但是,我也有几个集成测试。那些正在访问本地 firebase 模拟器 (localhost:8080)。

例如,在测试 Firestore 规则时,我只是调用 db.collection('path').add(model),这会触发模拟器进程中的可调用函数。

测试通过这个命令运行:firebase emulators:exec 'mocha --config spec/.mocharc.yml 首先,它正在初始化模拟器,然后运行测试。据我了解,这些是不同的过程。所以在 mocha 过程中,我可以使用模块进行存根、模拟。另一方面,在模拟器进程中,函数、模块、依赖项已经按原样加载。因此,当我在 mocha 测试套件中运行此测试脚本以测试 firestore 规则时:

await assertSucceeds(db.doc('stores').set(store));

它实际上运行处理程序并将请求发送到谷歌云 DNS。有没有人遇到过这样的问题?提前致谢。

【问题讨论】:

    标签: firebase google-cloud-firestore mocha.js firebase-security sinon


    【解决方案1】:

    我也面临同样的情况。我的计划是让 Cloud Function 使用存根服务初始化自身,该服务将在 NODE_ENV=test 时记录它自己对 Firestore 中的 log 集合的调用。然后测试将通过查询该集合来检查呼叫是否被记录。

    test('fanOutCategoryFields', async () => {
      // Initialize Firebase and seed test data
      const app = await setup({
        'categories/1': {
          name: 'Some Name',
        },
        'posts/1': {
          categoryId: '1',
        },
      })
    
      // Update a document (will trigger the Cloud Function)
      await app
        .firestore()
        .collection('categories')
        .doc('1')
        .update({ name: 'New Name' })
    
      // Wait for the Cloud Function to run
      await new Promise(resolve => setTimeout(resolve, 3000))
    
      // Query the collection where function calls are recorded
      const calls = await app
        .firestore()
        .collection('_calls')
        .get()
        .then(snap => snap.docs.map(snap => snap.data()))
    
      // Check if Algolia was called with the expected arguments
      expect(calls).toEqual([
        {
          fn: 'algolia.update',
          args: ['products', '1', { categoryName: 'New Name' }],
        },
      ])
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-12
      • 1970-01-01
      • 2017-07-21
      • 2018-11-23
      • 1970-01-01
      • 2019-09-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多