Search code examples
javascriptnode.jsjasmine-node

Jasmin test if callback parameter is called


so i have a function which checks if a checksum is changed and if so it calls the callback which is provided by a parameter.

var watchFileChange = function watchFileChange(oldChecksum, callback){
  // some code about checking checksum
  if(oldChecksum != newChecksum){
    callback()
  }
}
exports.watchFileChange = watchFileChange;

my Jasmin specs looks like this.

var t = require('../server.js');
describe("watchFileChange", function() {

    spyOn(t.watchFileChange, 'Callback');

    var file_false = {
      'foo.txt': 'd41dcccc8f00b204e9800998ecf8427e'
    }
    var file_true = {
      'foo.txt': 'd41d8cd98f00b204e9800998ecf8427e'
    }

    function Callback() {
      console.log("Callback Called")
    }

    it("Checksum is not right, it should call Callback function", function() {
            watchFileChange(file_false, Callback);
            expect(Callback).toHaveBeenCalled();
    });

  });

But it just doesn't work that way because Callback is not defined i get that. So my question is there a way to check if the by parameter provided callback is called?


Solution

  • You can create a fake object where you can define you callback function, and then pass it as the argument

    var init = {
      callback: function() {
        console.log("Callback Called")
      }
    };
    
    describe("watchFileChange", function() {
      beforeEach(function() {
        spyOn(init, 'callback');
      });
    
      //...  
    
      it("Checksum is not right, it should call Callback function", function() {
         watchFileChange(file_false, init.callback);
         expect(init.callback).toHaveBeenCalled();
      });
    });