Whats the best way to test with Jasmine that an inherited method has been called?
I am only interested in testing whether or not it has been called as I have unit tests set up for the base class.
example is:
YUI().use('node', function (Y) {
function ObjectOne () {
}
ObjectOne.prototype.methodOne = function () {
console.log("parent method");
}
function ObjectTwo () {
ObjectTwo.superclass.constructor.apply(this, arguments);
}
Y.extend(ObjectTwo, ObjectOne);
ObjectTwo.prototype.methodOne = function () {
console.log("child method");
ObjectTwo.superclass.methodOne.apply(this, arguments);
}
})
I want to test that ObjectTwo's inherited methodOne has been called.
Thanks in advance.
To do this you can spy the method in the prototype of ObjectOne
.
spyOn(ObjectOne.prototype, "methodOne").andCallThrough();
obj.methodOne();
expect(ObjectOne.prototype.methodOne).toHaveBeenCalled();
The only caveat of this method is that it won't check if methodOne
was called on the obj
object. If you need to make sure it was called on obj
object, you can do this :
var obj = new ObjectTwo();
var callCount = 0;
// We add a spy to check the "this" value of the call. //
// This is the only way to know if it was called on "obj" //
spyOn(ObjectOne.prototype, "methodOne").andCallFake(function () {
if (this == obj)
callCount++;
// We call the function we are spying once we are done //
ObjectOne.prototype.methodOne.originalValue.apply(this, arguments);
});
// This will increment the callCount. //
obj.methodOne();
expect(callCount).toBe(1);
// This won't increment the callCount since "this" will be equal to "obj2". //
var obj2 = new ObjectTwo();
obj2.methodOne();
expect(callCount).toBe(1);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With