我有一个名为firestore-mock.js
的模拟功能模块,其代码为:
var firestore = (function () {
var fsDB = {}
// ...
return {
"batch": batch,
"collection": collection,
"db": fsDB, // This does not work
// "db": (() => fsDB)(), // This works
"path": _pathComp,
"batchData": batchData
}
})()
module.exports = firestore
在我的测试文件中,我正在导入模块并将其分配为模拟:
// ..
const firestore = require("./firestore-mock")
describe('Cloud Functions', () => {
let myFunctions, adminInitStub
before(() => {
admin.initializeApp()
adminInitStub = sinon.stub(admin, 'initializeApp')
myFunctions = require('../index')
myFunctions.firestore = firestore
});
after(() => {
adminInitStub.restore()
test.cleanup()
});
it("write to firestore", () => {
firestore.collection("items").doc("p1").set({1:1})
firestore.collection("items").doc("p1").get().then((x) => console.log("get: %o", x))
console.log("firestore.db--->: %o", firestore.db)
})
})
我正在将before
中的模拟存储库添加为myFunctions.firestore = firestore
。如果返回值为firestore.db
,则{}
总是给出db: fsDB
,但如上所述,如果返回值是IIFE函数,它将返回fsDB
中的值。我不确定为什么要这么做。
为什么firestore.db
返回{}
而不是其设置值{1:1}
?
替代示例:
var fsDB = {}
var count = 0
function inc() {
count++
fsDB.count = count
}
module.exports = {
"inc": inc,
"fsDB": fsDB,
"count": count
}
it("write to firestore", () => {
firestore.inc()
console.log(firestore.fsDB) //{}
console.log(firestore.count) // 0
})