cloud functions test failing and context.params missing from the trigger function

Viewed 148

I am following this tutorial on unit testing firebase functions: https://fireship.io/lessons/testing-cloud-functions-in-firebase/

I added a unit test for a onCreate realtime database trigger and while the data arrives in it, the context.params come in as empty for the unit test. so I have

    test('checks that the user gets created', async () => {
    const userId = 'aaaaaaa';
    const path = `/users/${userId}`;
    const data = {
      "id": userId,
      "firstName": "Dan",
      "phoneNumber": "+11111111111",
      "carInfo": {
        "color": "blue",
        "make": "Ford",
        "model": "Focus",
        "plate": "BV-11-AAA"
      }
    };

    // Create a Database snapshot
    const snap = testEnv.database.makeDataSnapshot(data, path);

    // Execute it
    await wrapped(snap);

    const after = await admin.database().ref(path).once('value');
    const afterValue = after.val();

    expect(afterValue.phoneNumber).toBe('+11111111111')

  });

and my actual function (index.ts) being:

export const newUserCreated = database.ref('/users/{userId}').onCreate(async (snapshot: DataSnapshot, context) => {
    console.log('context params : ', context.params);
    const user = snapshot.val();
    await createStripeCustomerHandler(user, snapshot.key);
});

I get the actual payload in my function's handler, BUT:

There's 2 issues with it:

  1. It does not actually perform the save into the database, so the test itself fails (afterValue is null) (might be intended behaviour actually. not sure)
  2. The context params come in as empty when executing the unit test, so it prints out context params : {}. do I need to send the params for the context manually? from the testEnv.database.makeDataSnapshot command?

Am I doing something wrong or am I missing anything? Thank you in advance.

1 Answers

Today, more than two years later, I had the same problem and found a solution hiding in plain sight in the docs.

So here is the answer in case anybody finds this and have not seen the solution in the docs.

In the docs there are multiple ways to pass data to a function under test: https://firebase.google.com/docs/functions/unit-testing

For your current case you could have used this way to call wrapped in order to pass the params to the function during the test.

wrapped(data, {
  params: {
    userId: '234234'
  }
});
Related