Unit testing Firebase函数脱机测试存根
我正在脱机模式下编写firebase数据库onWrite触发器函数的测试,使用文档和中建议的存根 但是我不知道如何在触发器中的数据中存根多个Unit testing Firebase函数脱机测试存根,unit-testing,firebase,google-cloud-functions,sinon,Unit Testing,Firebase,Google Cloud Functions,Sinon,我正在脱机模式下编写firebase数据库onWrite触发器函数的测试,使用文档和中建议的存根 但是我不知道如何在触发器中的数据中存根多个.child().val()。以下是我创建数据对象的进度: let data={ before: { val : ()=> null, }, after:{ val: ()=> {/*after data h
.child().val()
。以下是我创建数据对象的进度:
let data={
before: {
val : ()=> null,
},
after:{
val: ()=> {/*after data here */},
child: {
"child1": "How have value here from val",
"child2": "How have value here from val"
}
}
}
因为我的函数有点复杂,所以从传入数据中有很多值读取(2到3级嵌套),然后还有对数据库的多重访问
那么,有没有简单的方法来存根所有这些电话?还是存根只适用于数据简单、对数据库的读取权限较少的函数
备注:我也使用了在线模式测试,但这会改变我无法恢复的数据库状态,因此使用firestore测试功能并不容易。我花了很多精力尝试了不同的模式,最终采用了这个策略
collectionQuery
,docQuery
等的函数如果有帮助,请告诉我:)因此,您建议使用联机模式,单独测试部分功能。这在只读的情况下看起来不错,但是如果存在对数据库的写入,那么如何测试它,因为这会改变数据库的状态。我认为我的解决方案在写入方面提供了灵活性。如果您不想测试实际的数据库,那么您就不会删除编写的函数。否则,您将其删除,并使用间谍检查函数是否按预期调用。@UmarHussain您最终使用了什么策略-您觉得我的答案有用吗?@DauleDK,我忍不住想知道为什么要传递afs参数:S@BorjaGorriz在同一运行时对不同的firebase实例使用我的函数
/**
* The purpose of this relatively simple function is to query firestore!
* By wrapping the operation in a helper function, it becomes much easier to test.
* @export
* @template T Provide the variable type for the function
* @param {FirebaseFirestore.Firestore} afs The firestore instance, usefull for switching between functions/admin
* @param {FirebaseFirestore.Query} query The query to perform. By accepting a query, it becomes very flexpible
* @returns {Promise<Array<T>>} The result as an array
*/
export async function collectionQuery<T>(afs: FirebaseFirestore.Firestore, query: FirebaseFirestore.Query): Promise<Array<T>> {
try {
if (afs == null || query == null) {
throw new Error(`You must provide an firestore instance, or a query`);
}
const snapshot = await query.get();
const returnData: T[] = snapshot.docs.map((doc) => doc.data() as T);
return returnData;
} catch (error) {
throw new Error(`collectionQuery failed unexpected with: ${error.message}`);
}
}
jest.spyOn(firehelpers, 'collectionQuery').mockReturnValue([]} // simulate no data returned by query
jest.spyOn(firehelpers, 'collectionQuery').mockReturnValue([{foo: 'bar'}]} // One result returned