Adrian Chen

How to Settimeout in Jasmine 2

jasmine, tdd, test, timeout

The waitsFor funciton for asynchronous specs have been removed in Jasmine 2, instead we have a done callback argument that when present, will make Jasmine consider its coresponding block as asynchronous, and waits for it to be invoked before timing out or finishing the spec, very similar to how Mocha does it’s async tests.

1
2
3
4
5
6
7
8
describe "When fetched", ->
  beforeEach: (done)->
      account.fetch
          success: ->
              done()

  it "should update its stock price", ->
      expect(account.name).toEqual("Adrian")

This is all well and good, until I ran into a problem when doing intergration test with my app that includes thrid party library that I can’t really dig into, in mycase it was the Google Maps API. To use the done syntax, you require to have an entry point of knowing when your ajax call finishes to raise the done event.

To get round this you need to use the good old setTimeout method like so:

1
2
3
4
5
6
7
8
9
10
11
12
describe "on running a search", ->
    it "returns places", (done) ->
        places = null
        $(searchBox).on "placesChanged", (e, data) ->
          places = data
          expect(places.length).toBeGreaterThan 0
          done()
        setInputVal = ->
          input.val("London")
          input.focus().simulate("keydown", { keyCode: 13 })
        # No way for us to know exactly when the Google SearchBox is ready for input ...
        setTimeout(setInputVal, 1000)

In my opinion the waitsFor function still has a place in Jasmine, the done callback syntax doesn’t completely replaces waitsFor.

Comments