使用 Jasmine 模拟 firebase 调用

Mocking a firebase calls using Jasmine

我正在寻找对 firebase 数据库的 spyOn 调用。我有一个包装 firebase 调用的 FireFunc 文件。但是,当我使用 spyOn 检查方法时,它 returns 是常规结果。这是怎么回事?

var FireFunc = require("../js/services-fb-functions.js");

describe('Firebase Testing Suite', function() {
    var firebase;
    var testPath;
    var testResult = {};

    beforeAll(function() {
        var firebaseFunctions = ['check']
        firebase = jasmine.createSpyObj('firebase', firebaseFunctions)

        firebase.check.and.callFake(function() {
            return 2
        });
   });

   describe('check', function() {
    it('is working?', function() {
        var x = FireFunc.zset()
        expect(x).toBe(3); // THIS IS RETURNING 1... which means the spyOn doesn't work for me !
    });
});

这是我的代码 (js/services-fb-functions.js)

var firebase = {};
firebase.check = function() {
    return 1;
}

module.exports = {
    zset: function() {
        return firebase.check();
    }
}

问题是您没有向被测对象提供 firebase 对象的模拟版本。 firebase 对象存在于 js/services-fb-functions.js 中,它纯粹是内部的,不会以任何方式暴露出来进行测试。好的做法通常是使用 dependency injection for providing internal objects that you wish to mock out during tests. I've adapted your code slightly to work with JSFiddle and Jasmine 1.3, so please excuse my limited JS skills (there are definitely more elegant ways of exposing the internal object), but this JSFiddle should demonstrate my point: Simple Jasmine example using spies