6

用 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);
    }
})

我想测试 ObjectTwo 的继承 methodOne 是否已被调用。

提前致谢。

4

1 回答 1

4

为此,您可以在ObjectOne.

spyOn(ObjectOne.prototype, "methodOne").andCallThrough();
obj.methodOne();
expect(ObjectOne.prototype.methodOne).toHaveBeenCalled();

此方法的唯一警告是它不会检查对象是否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);
于 2013-03-03T19:18:52.917 回答