![](/img/trans.png)
[英]Firebase HTTPS callable function context.auth is always null when used with custom token auth
[英]Send auth context to firebase callable function in unittest
我一直在從事一個 firebase 項目,在該項目中我創建了一個在 firestore 中創建文檔的雲功能。 這是功能 -
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
參數進行了身份驗證。 當我在我的網絡應用程序中使用它時,一切正常,但我一直試圖找出一種方法來為這個函數創建一個單元測試。 我的問題是我無法真正弄清楚如何創建經過身份驗證的請求以確保我的功能不會每次都失敗。 我試圖在網上查找任何文檔,但似乎找不到任何文檔。
提前致謝!
您可以使用firebase-functions-test
SDK 對您的函數進行單元測試。 該指南提到您可以模擬傳遞給您的函數的eventContext
或context
參數中的數據。 這適用於模擬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');
});
});
});
});
讓我知道這是否有用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.