Не удалось получить значение переменной db внутри функции мокко - PullRequest
0 голосов
/ 13 марта 2019

У меня есть модуль фиктивных функций под названием 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
})
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...