use*_*014 6 inheritance jasmine
什么是使用Jasmine测试继承方法的最佳方法?
我只对测试它是否被调用感兴趣,因为我已经为基类设置了单元测试.
例如:
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);
}
})
Run Code Online (Sandbox Code Playgroud)
我想测试ObjectTwo的继承方法是否已被调用.
提前致谢.
为此,您可以监视 原型中的方法ObjectOne
。
spyOn(ObjectOne.prototype, "methodOne").andCallThrough();
obj.methodOne();
expect(ObjectOne.prototype.methodOne).toHaveBeenCalled();
Run Code Online (Sandbox Code Playgroud)
此方法的唯一警告是它不会检查是否在对象methodOne
上调用obj
。如果您需要确保它是在obj
对象上调用的,您可以这样做:
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);
Run Code Online (Sandbox Code Playgroud)