无法获取Mocha函数中db变量的值

时间:2019-03-13 09:22:44

标签: javascript node.js mocha

我有一个名为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
})

0 个答案:

没有答案