Take the 2-minute tour ×

I am beginner of CoffeeScript and Jasmine. I tried to test a simple class as below:

class Counter
    count: 0

    constructor: ->
        @count = 0

    increment: ->

    decrement: ->

    reset: ->
        @count = 0

root = exports ? this
root.Counter = Counter

Then, I wrote test code as below:

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

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

The second test always failed and the message was below:

Expected 0 to be 1.

Thank you for your kindness.

share|improve this question
add comment

1 Answer

up vote 3 down vote accepted

You need to use the pre-increment and pre-decrement forms if you want your increment and decrement methods to return the updated values:

increment: -> ++@count
decrement: -> --@count

x++ yields the value of x and then increments x so this:

return x++

is equivalent to:

y = x
x = x + 1
return y

whereas this:

return ++x

is like this:

x = x + 1
return x

So Jasmine is right and has nicely uncovered a bug in your code.

For example, this code:

class Counter
    constructor: (@count = 0) ->
    incr_post: -> @count++
    incr_pre:  -> ++@count

c1 = new Counter
c2 = new Counter    


will give you 0 and 1 (in that order) in the console even though @count will be 1 inside both c1 and c2 when you're done.

share|improve this answer
add comment

Your Answer


