2012-09-27 55 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