I am currently using Firebase Cloud Functions and MongoDB to create my app and here are the files that I have.
module.exports.updateUser = functions.https.onCall(async (data, context) => {
try {
// Retrieve the relevant data from the arguments
const { username, name, phone, postal, address, gender, dob } = data;
const userID = contect.auth.uid;
// Setting up the database
await connect(process.env.DB_URL);
// Create a schema for the database
const userSchema = new Schema({
name: String,
username: String,
phone: String,
postal: String,
address: String,
gender: String,
dob: String,
firebaseUID: String,
});
// Create a new database model
const User = model("users", userSchema);
const user = new User({
name: name,
username: username,
phone: phone,
postal: postal,
address: address,
gender: gender,
dob: dob,
firebaseUID: userID,
});
// Saving the user information
await user.save();
return { success: true, response: user };
} catch (e) {
return { success: false, error: e };
}
});
and I would like to test this file. Currently, my test code is as follows:
// Require and initialize firebase-functions-test. Since we are not passing in any parameters, it will
// be initialized in an "offline mode", which means we have to stub out all the methods that interact
// with Firebase services.
const test = require("firebase-functions-test")();
// Chai is a commonly used library for creating unit test suites. It is easily extended with plugins.
const assert = require("chai").assert;
// Sinon is a library used for mocking or verifying function calls in JavaScript.
const sinon = require("sinon");
// Require mongoose so that we can stub out some of its function
const mongoose = require("mongoose");
const { expect } = require("chai");
describe("Test addUser", () => {
let myFunction, mongooseSaveStub, mongooseConnectStub;
before(() => {
mongooseSaveStub = sinon.stub(mongoose, "save");
mongooseConnectStub = sinon.stub(mongoose, "connect");
myFunction = require("../index").updateUser;
});
after(() => {
mongooseInitStub.restore();
test.cleanup();
});
it("should pass", async (done) => {
const updateUser = test.wrap(myFunction);
const data = { name: "John Higgens" };
const context = { auth: { uid: "mock" } };
await updateUser(data, context).then((result) => {
expect(result.success).toBe(true);
done();
});
});
});
Can I ask 1) how I can test my cloud function, 2) how do I mock or stub the database and 3) where did I do wrongly? The current error that I have is:
Error [ERR_PACKAGE_PATH_NOT_EXPORTED]: Package subpath './lib/encoder' is not defined by "exports"