2016-12-01 66 views
0

我創造了這個小片的代碼被執行最好的方式來測試,如果內部對象的方法

function myFunction() { 
    var myObject = { 
    objProperty: "string", 
    objMethod: function() { 
     return myObject.objProperty; 
    } 
    }; 

    return myObject.objMethod(); 
}; 

現在我試圖讓單元測試,如果代碼工作將檢查作爲它應該:

describe("checking syntax and function integrity", function(){ 

    // called before each spec is ran 
    before(function(){ 

    }); 

    it ("should return 'string' when myFunction is called", function(){ 
     Test.assertEquals(myFunction(), 'string', 'myFunction did not return "string"'); 
    }); 

    it ("should check if myObject.objMethod was called", function(){ 

    }); 
}); 

我的問題:是否可以檢查myObject.objMethod是否被調用?我正在使用由CodeWars提供的測試框架。

Here is a link to their test framework

+1

'Test.callCount(methodName)→Integer' 返回調用Test方法的次數。創建需要測試測試方法使用情況的kata時非常有用。在使用Test助手方法時,在kata解決方案中不允許使用。您可以簡單地測試是否有任何禁止呼叫。 – n00dl3

+0

您能否提供一個關於您認爲應該如何寫測試的答案? – mdarmanin

+0

嗯實際上它似乎只涉及測試方法... – n00dl3

回答

0

看來這個測試框架不支持這樣的事情。但是你可以做這樣的事情:

it ("should check if myObject.objMethod was called", function(){ 
    let oldMethod=myObject.myMethod; 
    let callCount=0; 
    myObject.myMethod=function(){ 
    callCount++; 
    oldMethod.apply(this,arguments); 
    } 
    //do stuff that should trigger the method 
    //and then... check!!! : 
    Test.assertEquals(callCount,1); 
}); 

編輯:我沒有看到myObject的是內部myFunction(),對不起。所以答案是:

你不能!由於myObject不能從您的測試環境訪問。在這裏測試它是沒有意義的,因爲它在你的函數內部。你可以(也應該)測試的唯一的事情是MyFunction()調用返回一個字符串,也許是一個匹配一些隨機標準的字符串。

如果至少它不是一個對象字面值,而是一個從構造函數實例化的對象,它應該得到自己的測試,但這不是這種情況。

如果要測試myObject的行爲,使其可重用:創建一個MyObject()構造函數,或通過參數將對象傳遞給您的myFunction(myObject)調用。

+0

let oldMethod = myObject.myMethod; //返回ReferenceError:myObject未定義 – mdarmanin

+0

事實是,如果在測試中myObject不是實例化的,你無法測試。您的測試沒有任何意義,因爲您無法測試無法訪問的內容。 – n00dl3

相關問題