0

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?

BitKoch
  • 31
  • 7

1 Answers1

1

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();
  });
});
yoogeeks
  • 965
  • 8
  • 24
  • Yes! Thank you very much. May you can tell me why i need the beforeEach around the spyOn? – BitKoch Feb 17 '16 at 08:28
  • The `spyOn` function must be placed inside either `beforeEach` or `it` block where the `currentSpec` is set. Otherwise you'll get a "currentSpec is null" error. So if you have only one spec, you can put your spy directly inside `it` block, but if you're going to reuse your spy, it is better to share it via `beforeEach` block – yoogeeks Feb 17 '16 at 10:26
  • Ahh i see. Thank you very much again. – BitKoch Feb 17 '16 at 11:22