Given the following code (with Jasmine included in the page):
function MyCtorFn() {
this.myMethod = function() {
console.log("hello world")
}
}
//arrange
var myCtrFn = new MyCtorFn();
spyOn(myCtrFn, 'myMethod');
//act
myCtrFn.myMethod();
Why does the following return undefined?
myCtrFn.myMethod.callCount
Given the following code (with Jasmine included in the page):
function MyCtorFn() {
this.myMethod = function() {
console.log("hello world")
}
}
//arrange
var myCtrFn = new MyCtorFn();
spyOn(myCtrFn, 'myMethod');
//act
myCtrFn.myMethod();
Why does the following return undefined?
myCtrFn.myMethod.callCount
Share
Improve this question
edited Jan 7, 2014 at 18:34
Charles
51.5k13 gold badges106 silver badges144 bronze badges
asked Jan 7, 2014 at 13:50
Ben AstonBen Aston
55.8k69 gold badges220 silver badges349 bronze badges
2 Answers
Reset to default 5.callCount
is a property of the spy
.
function MyCtorFn() {
this.myMethod = function() {
console.log("hello world")
}
}
//arrange
var myCtrFn = new MyCtorFn();
var spy = spyOn(myCtrFn, 'myMethod');
//act
myCtrFn.myMethod();
spy.callCount; // 1
Actually, it's very strange that it doesn't work, since the spyOn
method should replace the original method with the spy.
See https://github./pivotal/jasmine/blob/master/lib/jasmine-core/jasmine.js
line 582
.
Personally I think that is very strange behavior. This would cause all kinds of inpatibilities with other frameworks. What if you had two instances of jasmine and they both try to spy on the same function? Very strange.
This is why I assumed the properties were only on the spy.
The whole point of a spy is that you're undetectable right?
var trustedFunction = function () {};
var obj = {
foo: trustedFunction
}
spyOn(obj, "foo");
obj.foo === trustedFunction; // false? BUSTED
Perhaps a spy is not the right analogy. A CallTrackerWrapper
would be a much less nefarious and more humble name.
The documented way to get the call count for a spy is via the calls
property:
myCtrFn.myMethod.calls.count() // 1
Documentation: http://jasmine.github.io/2.0/introduction.html#section-23
Looking at the sources, it seems this information is not available anywhere else: https://github./pivotal/jasmine/blob/master/src/core/CallTracker.js https://github./pivotal/jasmine/blob/master/src/core/base.js#L75