0

I'm looking to spyOn calls to the firebase database. I have a FireFunc file that wraps firebase calls. However, when I go to spyOn the check method, it returns the regular result. What's going on here?

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 !
    });
});

This is my code (js/services-fb-functions.js)

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

module.exports = {
    zset: function() {
        return firebase.check();
    }
}
1dolinski
  • 479
  • 3
  • 9
  • 29

1 Answers1

1

The issue is that you have not supplied the mocked version of the firebase object to your object under test. The firebase object as it exists in js/services-fb-functions.js is purely internal is not exposed in any way for testing. Good practice would generally be to use 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

dkichler
  • 307
  • 1
  • 11
  • Tho this is still a disappointment that firebase still does not work in a TDD stratergy. – Doug Thompson - DouggyFresh Apr 28 '20 at 10:16
  • Even using npm install @firebase/testing@0.19.2 to pull in the latest testing SDK is of little help. I am not sure of the use of a fake/spy when you say calling the firebase code will always return a value of '3' when in fact firebase real, will not work in jasmine, whatever it is. There is a little more guidance in this link https://stackoverflow.com/questions/46229787/testing-cloud-functions-for-firebase-with-jasmine-and-typescript - but it still feel like The Dark Arts... – Doug Thompson - DouggyFresh Apr 28 '20 at 10:23