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 に答える