2014-04-03 186 views
1

這裏測試嵌套的對象是我的測試茉莉花

describe("setTimer", function() { 
     it("set status timer values from parameters and sets timer.visible to true", function(){ 
     var boxNumber = 1, 
      time = 15; 
     myObject.setTimer(boxNumber, time); 
     expect(anotherObject.status.timer.boxNum).toBe(boxNumber); 
     expect(anotherObject.status.timer.seconds).toBe(time); 
     }) 
    }); 

下面是代碼

setTimer: function (boxNum, seconds) { 
    anotherObject.status.timer.boxNum = boxNum; 
    anotherObject.status.timer.seconds = seconds; 
    anotherObject.status.timer.visible = true; 
    }, 

以下是錯誤我得到

TypeError: Cannot read property 'timer' of undefined 

我嘗試設置使用對象anotherObject = {}我試過設置anotherObject.status = {},最後試着設置anotherObject.status.timer = {},howeve r我仍然得到錯誤。任何想法,我怎樣才能嘲笑對象?

+0

目前還不清楚「anotherObject」是從哪裏提供的。這是否在您的主要「describe」函數中?別的地方?上面的代碼片段似乎沒有提供足夠的上下文來回答問題。 –

+0

@AndrewTheken,anotherObject實際上是一個全局對象,它是由當前測試範圍之外的另一種方法創建的。這就是爲什麼我認爲我可能不得不嘲笑測試範圍內的整個對象。 – zmanc

+0

這是在節點或瀏覽器,或其他地方? –

回答

1

不知道如何/其中'anotherObject'的構造我認爲你需要初始化'anotherObject',然後再在你的測試中執行setTimer函數。

你有一個init()或setup()函數存在於'anotherObject'上,它會爲你初始化'timer'對象嗎?

雖然該方法看起來像只是試圖確保該方法設置所有相應的屬性。

您可以在您的測試

describe("setTimer", function() { 
    it("set status timer values from parameters and sets timer.visible to true", function(){ 
    var boxNumber = 1, 
     time = 15; 

    //Initialize the anotherObject 
    anotherObject.status = { timer : {} } 

    myObject.setTimer(boxNumber, time); 
    expect(anotherObject.status.timer.boxNum).toBe(boxNumber); 
    expect(anotherObject.status.timer.seconds).toBe(time); 
    }) 
}); 

這當然附帶了現在已經定義使用全球範圍內測試內的「anotherObject」的告誡調用SetTimer的(因爲排除了var之前執行以下操作在JavaScript中的任何變量定義使其成爲全局範圍)。這可能會影響其他測試用例,這些測試用例希望以某種方式設置計時器對象,但是您的測試用例現在分別將計時器值設置爲1和15(可能有很多其他值取決於測試用例在做什麼)。

因此,要解決這個問題,復位「anotherObject」開頭或你的測試結束將與污染有助於

afterEach(function(){ 
    anotherObject.status = { timer : {} } 
}) 

beforeEach(function(){ 
    anotherObject.status = { timer : {} } 
}) 

當然,如果你有一個init( ),可以使用的'anotherObject'上的create()或setup()函數當然會給你更真實的結果,因爲對象會更接近它在生產中的樣子。

+0

完美,謝謝。我不能再給予17小時的賞金,但我會盡快辦到。 – zmanc

0

您不是在源代碼和測試代碼中使用同一個「anotherObject」對象。

每個代碼都有它自己的對象,並且其中的一個設置值不會在另一箇中設置。