Jest中依赖Firestore模拟器时的Promise异常问题
Firestore模拟器在Jest中runTransaction报错的解决方法
问题现象
使用Google Cloud Firestore模拟器时,调用global.db.runTransaction(async () => 100)在Node环境可正常运行,但在Jest的test函数中执行时抛出错误:
Error: You must return a Promise in your transaction()-callback.
原因分析
Firestore库内部会校验事务回调的返回值是否为Promise实例。在Jest环境中,async () => 100返回的对象虽然打印显示为Promise { 100 },但通过instanceof Promise判断结果为false,导致被判定为非Promise。不过单独编写测试验证async函数返回Promise的逻辑是可以通过的。
解决方案
最初尝试在jest.config.js中直接初始化global.db的方式无效,最终通过以下步骤解决:
- 创建
setup.js文件,在其中初始化全局db实例 - 配置Jest的
setupFilesAfterEnv加载该setup.js文件
另外,Jest的globals配置项因Firestore实例无法被JSON序列化,无法用于初始化全局db。
相关代码片段
原无效的jest.config.js配置
module.exports = async () => { const Firestore = require("@google-cloud/firestore"); global.db = new Firestore({ projectId: process.env.GOOGLE_CLOUD_PROJECT }); return {} }
有效的setup.js内容
const Firestore = require("@google-cloud/firestore/build/src"); global.db = new Firestore({ projectId: process.env.GOOGLE_CLOUD_PROJECT });
内容的提问来源于stack exchange,提问作者AmitA
相关产品推荐
相关产品推荐

