2012-09-27 58 views
1

我是CoffeeScript和Jasmine的初學者。我試圖測試如下一個簡單的類:我非常簡單的茉莉花測試失敗,消息'預期0爲1'。

class Counter 
    count: 0 

    constructor: -> 
     @count = 0 

    increment: -> 
     @count++ 

    decrement: -> 
     @count-- 

    reset: -> 
     @count = 0 

root = exports ? this 
root.Counter = Counter 

於是,我寫了如下測試代碼:

describe("Counter", -> 
    counter = new Counter 
    it("shold have 0 as a count variable at first", -> 
     expect(counter.count).toBe(0) 
    ) 

    describe('increment()', -> 
     it("should count up from 0 to 1", -> 
      expect(counter.increment()).toBe(1) 
     ) 
    ) 
) 

第二個測試總是失敗,該消息是以下:

Expected 0 to be 1. 

謝謝你的好意。

回答

3

你需要的,如果你希望你的incrementdecrement方法返回更新的值使用預增和預減的形式:

increment: -> [email protected] 
decrement: -> [email protected] 

x++產生的x值,然後遞增x所以這:

return x++ 

等同於:

y = x 
x = x + 1 
return y 

,而這一點:

return ++x 

是這樣的:

x = x + 1 
return x 

所以茉莉花是正確的,已經很好地發現代碼中的錯誤。

例如,this code

class Counter 
    constructor: (@count = 0) -> 
    incr_post: -> @count++ 
    incr_pre: -> [email protected] 

c1 = new Counter 
c2 = new Counter  

console.log(c1.incr_post()) 
console.log(c2.incr_pre()) 

會給你0並在控制檯1(按順序),即使@count1c1c2內時,即可大功告成。