Ashley Coolman
Ashley Coolman

Reputation: 11585

Javascript testing: Passing around Jasmine 2.0's "done" function - not what I expected

I'm relatively new to asynchronous testing, and the following behavior surprised me. What am I missing?I'd appreciate someone pointing me in the right direction

If this works [Coffeescript]:

# Works
describe "Asynchronous specs", ->
    o = {}    
    beforeEach (done) ->        
        o.async = ->
            console.log "Finished"

        spyOn o, "async"
        setTimeout (->
            o.async()
            done()
        ), 1500

    it "async executed", ->        
        expect o.async
            .toHaveBeenCalled()

Why doesn't passing the done() function as a parameter also work?

# doesnt work: Test times out
describe "Asynchronous specs", ->
    o = {}    
    beforeEach (done) ->        
        o.async = (passedDone)->
            passedDone()
            console.log "Finished"

        spyOn o, "async"
        setTimeout (=>
            o.async done
        ), 1500

    it "async executed", ->        
        expect o.async
            .toHaveBeenCalled()

Upvotes: 0

Views: 195

Answers (1)

hhelwich
hhelwich

Reputation: 200

The async method will never be called in the second example because it is spied on. You can change

spyOn o, "async"

to

spyOn(o, "async").and.callThrough()

so the method is spied and also all calls are delegated to the async method.

Upvotes: 1

Related Questions