单元测试 Firebase Cloud Function 第二代:makeDataSnapshot refPath 不起作用

问题描述 投票:0回答:1

使用mocha为以下云函数创建测试时

//index.js
exports.cloudFnTest = onValueCreated({
  timeoutSeconds: 30,
  memory: '128MiB',
  instance: "test-instance",
  ref: "abc/{uid}"
}, (event) => {
  // Code
});

我按照以下方式编写了测试:

//index.test.js
require('dotenv').config();
const test = require('firebase-functions-test')({
  databaseURL: 'my-database-url',
  projectId: 'my-project-id',
}, './serviceAccountKey.json');

const myFunctions = require('../index.js'); // relative path to functions code

const { expect } = require('chai');

describe("Test Cloud Function", () => {

  it("Test 1", async () => {
    const wrapped = test.wrap(myFunctions.cloudFnTest);
    const data = {
      ab: 176
    }

    const eventData = {
      data: test.database.makeDataSnapshot(data, 'xyz/live/ui')
    }

    // cloud fn gets executed even for wrong ref as xyz/live/ui does not match abc/{uid}
    p = await wrapped(eventData)
  });

})

我想知道为什么即使引用错误,云函数也会被执行,而不是云函数。

如何测试不应为此参考执行云函数:xyz/live/ui

预期结果:

我希望云函数不会因错误的引用而执行,而只会因正确的引用而执行。 我该怎么做

node.js unit-testing firebase-realtime-database google-cloud-functions mocha.js
1个回答
0
投票

修改测试,在调用云函数之前检查引用

    require('dotenv').config();
const test = require('firebase-functions-test')({
  databaseURL: 'my-database-url',
  projectId: 'my-project-id',
}, './serviceAccountKey.json');

const myFunctions = require('../index.js'); // relative path to functions code

const { expect } = require('chai');

describe("Test Cloud Function", () => {

  it("Should not execute for wrong ref", async () => {
    const wrapped = test.wrap(myFunctions.cloudFnTest);
    const data = {
      ab: 176
    }

    const eventData = {
      data: test.database.makeDataSnapshot(data, 'xyz/live/ui')
    }

    // Ensure the cloud function is not executed for the wrong ref
    await expect(wrapped(eventData)).to.not.be.eventually.fulfilled;
  });

  it("Should execute for correct ref", async () => {
    const wrapped = test.wrap(myFunctions.cloudFnTest);
    const data = {
      ab: 176
    }

    const eventData = {
      data: test.database.makeDataSnapshot(data, 'abc/123') // Provide a valid reference
    }

    // Ensure the cloud function is executed for the correct ref
    await expect(wrapped(eventData)).to.be.eventually.fulfilled;
  });

});

此方法有助于根据事件数据中提供的参考来验证云函数的行为。

© www.soinside.com 2019 - 2024. All rights reserved.