Firebase 功能是离线测试存根



我正在离线模式下使用存根为Firebase数据库onWrite触发函数编写测试,如文档和github示例中的建议。

但是我很困惑如何在触发器中的数据中存根多个.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 级嵌套(,然后还有对数据库的多次访问。

那么有没有简单的方法来存根所有这些呼叫?还是存根仅适用于具有简单数据且对数据库的读取访问权限较少的函数?

PS:我也使用了在线模式测试,但这改变了我无法恢复的数据库的状态

使用 firestore 测试函数并不容易。我用了很多精力去尝试不同的模式,最终得到了这个策略。

  1. 在项目中创建泛型方法,用于提取数据。例如一个名为collectionQuerydocQuery等的函数。
  2. 在联机模式下初始化函数测试。(这样你的测试就不会无休止地抱怨事情没有被存根和嘲笑:)(
  3. 现在,在测试中,您可以简单地监视步骤 1 中的函数。如果您创建函数,以便它们返回值,则变得非常容易。

collectionQuery 函数(打字稿(示例:

/**
* 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,所以像这样:

jest.spyOn(firehelpers, 'collectionQuery').mockReturnValue([]} // simulate no data returned by query
jest.spyOn(firehelpers, 'collectionQuery').mockReturnValue([{foo: 'bar'}]} // One result returned

此策略使测试读取和写入 db/firestore 的函数变得容易。如果需要,也可以与火力库上的存根结合使用。

让我知道它是否有帮助:)

最新更新