Reputation: 903
In the Jasmine 2.2 documentation I cannot understand the last spec that demonstrates the basic use of Spies.
In the beforeEach()
section we set bar = null
, then we spy on foo.setBar
and then we call foo.setBar
twice. I can't understand why bar === null
in the last spec. Shouldn't it be bar === 456
before the spy is torn down for the spec?
Here is the example:
describe("About a Spy", function(){
var foo, bar = null;
beforeEach(function() {
foo = {
setBar: function(value) {
bar = value;
}
};
spyOn(foo, "setBar"); // we spy
foo.setBar(123); // shouldn't bar === 123 here?
foo.setBar(456, 'another param'); // and bar === 456 here?
});
it("stops all execution on a function", function() {
// What, why, how?
expect(bar).toBeNull();
//I expected this to be the case, but it's not.
//expect(bar).toBe(456);
});
});
I must be misunderstanding how the beforeEach builds up and tears down the variable scope or perhaps there is a step where the variables within the describe
section get reset? Or were they never actually touched, because we used the spy function only and not the real function?
It would be very helpful if you could explain what exactly is going on with the variable bar
in this spec suit so I could understand why its value remains null in the last spec.
Thanks!
Upvotes: 5
Views: 1867
Reputation: 5535
If you look closely, you might realize that spyOn is replacing the original function with a spy that intercepts the function calls and tracks a lot of potentially useful information about them. The problem we run into above is that once we’ve replaced the original function, we’ve lost its capabilities. We can remedy that with andCallThrough. If you chain andCallThrough() after calling spyOn, the spy will then pass any calls to it through to the original function
http://www.joezimjs.com/javascript/javascript-unit-testing-with-jasmine-part-2/
Upvotes: 5