Reputation: 11
I'm new to jasmine and spies thing, hope you could point to the right direction.
I have an event listener that i want to cover with unit test:
var nextTurn = function() {
continueButton.addEventListener("click", displayComputerSelection)
};
nextTurn();
The general idea is to spy the 'displayComputerSelection' function .
it ("should call fn displayComputerSelection on continueButton click", function(){
spyOn(displayComputerSelection);
continueButton.click();
expect(displayComputerSelection).toHaveBeenCalled();
Since the basic structure of spies is spyOn(<object>, <methodName>)
i get a response No method name supplied
.
I've tried experimenting with jasmine.createSpy but couldn't make it work.
How would i substitute for the method that is expected?
Upvotes: 1
Views: 1734
Reputation: 11
The answer in my specific case was:
it ("should call displayComputerSelection on continueButton click", function(){
spyOn(window, "displayComputerSelection");
start(); //first create spies, and only then "load" event listeners
continueButton.click();
expect(window.displayComputerSelection).toHaveBeenCalled();
});
Browser seems to hook up global var/functions to the 'window' object, thus it is to be spied upon.
Upvotes: 0
Reputation: 9190
Your problem
In your scenario, the whole question is how or where is displayComputerSelection
defined, because this func is what you want to replace with your spy.
jasmine.createSpy()
It is jasmine.createSpy()
that you want. For instance, the following is an example for how you can use it - totally untested - no pun intended.
var objectToTest = {
handler: function(func) {
func();
}
};
describe('.handler()', function() {
it('should call the passed in function', function() {
var func = jasmine.createSpy('someName');
objectToTest.handler(func);
expect(func.calls.count()).toBe(1);
expect(func).toHaveBeenCalledWith();
});
});
Upvotes: 1