2012-09-27 93 views
-1

我是CoffeeScript和Jasmine的初學者。起初,我試圖通過測試與下面的代碼:遞增測試代碼應該是'++ @ count'?

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) 
     ) 
    ) 
) 

那麼善良的人告訴我,代碼應該如下:

class Counter 
    count: 0 

    constructor: -> 
     @count = 0 

    increment: -> 
     [email protected] 

    decrement: -> 
     [email protected] 

    reset: -> 
     @count = 0 

root = exports ? this 
root.Counter = Counter 

是的,這段代碼通過了測試。但我有一個問題,即前代碼比後代代碼更自然。我不知道如何確定這個問題。感謝您的幫助。

+1

你是什麼意思「更自然」?如果你只看到過後面的增量,那麼預先增量可能看起來是外來的,但它同樣有效。 –

+0

與你的問題有關的新問題,但'counter = new Counter'應該包含在'beforeEach'中。 – loganfsmyth

回答

1

,你可以更改您的代碼下面是關於返回值更清楚,如果你選擇堅持張貼增量

​​

,或者您可以將您的測試更改爲:

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

但那麼你不希望增量和減量的返回值反映@count的更新值

這裏是一個例子,可以使差異變得明顯ious: http://coffeescript.org/#try:class%20Counter%0A%20%20count%3A%200%0A%0A%20%20increment%3A%20-%3E%0A%20%20%20%20%40count%2B%2B%0A%20%20%20%20%40count%0A%20%20%0A%20%20inc%3A%20-%3E%0A%20%20%20%20%40count%2B%2B%0A%0A%20%20decrement%3A%20-%3E%0A%20%20%20%20--%40count%0A%0A%20%20dec%3A%20-%3E%0A%20%20%20%20%40count--%0A%0Acnt%20%3D%20new%20Counter%0Aalert%20cnt.increment()%0Aalert%20cnt.count%0Aalert%20cnt.inc()%0Aalert%20cnt.count%0Aalert%20cnt.decrement()%0Aalert%20cnt.count%0Aalert%20cnt.dec()%0Aalert%20cnt.count

2

這是前後增量之間的基本區別。 @count++將返回@count的值,然後遞增。 [email protected]將首先遞增並返回新值。如果您使用@count++,那麼這就是您的測試失敗的原因。更多關於increment and decrement operators