发送授权上下文到unittest中的firebase可调用函数



我一直在做一个firebase项目,在这个项目中我创建了一个云函数,可以在firebase中创建文档。这是函数-

export const createExpenseCategory = functions
.region("europe-west1")
.https.onCall(async (data, context) => { // data is a string
if (!context.auth?.uid) { // check that requesting user is authenticated
throw new functions.https.HttpsError(
"unauthenticated",
"Not Authenticated"
);
}
const res = await admin
.firestore()
.collection("/categories/")
.where("uid", "==", context.auth.uid)
.get();
const categoryExists = res.docs.find((doc) => doc.data().name === data); // check that there are not duplicates.
//  doc looks like this -
//  {
//    "name": "Food",
//    "uid": "some_long_uid"
//  }
if (categoryExists) {
throw new functions.https.HttpsError(
"already-exists",
`Category ${data} already exists`
);
}
return admin
.firestore()
.collection("/categories/")
.add({ name: data, uid: context.auth.uid });
});

可以看到,在函数的开头,我检查发送请求的用户是否使用context参数进行了身份验证。当我在我的web应用程序中使用它时,一切都很好,但我一直在试图找出一种方法来为这个函数创建一个unittest。我的问题是,我不能真正弄清楚如何创建一个经过身份验证的请求,以确保我的函数不会每次都失败。我试着在网上寻找任何文档,但似乎找不到。

提前感谢!

您可以使用firebase-functions-testSDK对函数进行单元测试。该指南提到可以模拟传递给函数的eventContextcontext参数中的数据。这用于模拟auth对象的uid字段:

// Left out authType as it's only for RTDB
wrapped(data, {
auth: {
uid: 'jckS2Q0'
}
});

该指南使用mocha进行测试,但您可以使用其他测试框架。我做了一个简单的测试,看看它是否可以工作,我可以将模拟uid发送给函数,它按预期工作:

index.js

exports.authTest = functions.https.onCall( async (data, context) => {
if(!context.auth.uid){
throw new functions.https.HttpsError('unauthenticated', 'Missing Authentication');
}
const q = await admin.firestore().collection('users').where('uid', '==', context.auth.uid).get();
const userDoc = q.docs.find(doc => doc.data().uid == context.auth.uid);
return admin.firestore().collection('users').doc(userDoc.id).update({name: data.name});
});

index.test.js

const test = require('firebase-functions-test')({
projectId: PROJECT_ID
}, SERVICE_ACCTKEY); //Path to service account file
const admin = require('firebase-admin');
describe('Cloud Functions Test', () => {
let myFunction;
before(() => {
myFunction = require('../index.js');
});
describe('AuthTest', () => {
it('Should update user name in UID document', () => {
const wrapped = test.wrap(myFunction.authTest);
const data = {
name: 'FooBar'
}
const context = {
auth: {
uid: "jckS2Q0" //Mocked uid value
}
}
return wrapped(data, context).then(async () => {
//Asserts that the document is updated with expected value, fetches it after update
const q = await admin.firestore().collection('users').where('uid', '==', context.auth.uid).get();
const userDoc = q.docs.find(doc => doc.data().uid == context.auth.uid);
assert.equal(userDoc.data().name, 'FooBar');
});
});
});
});

请告诉我这是否有用。

最新更新