How to test with process.nextTick

I am using Mocha to test some Node.js code and want to use process.nextTick() to call a callback of a method.

The Code

  @getNouns: (callback) ->
    @_wordnik.randomWords(
      includePartOfSpeech: 'noun',
      (e, result) ->
        throw new Error('Wordnik Failed') if e
        process.nextTick ->
          callback(result)
    )

The Test

it 'should call a callback with the response', (done) ->
      sinon.stub(Word._wordnik, 'randomWords').yields(null, [
                              {id: 1234, word: "hello"},
                              {id: 2345, word: "foo"},
                              {id: 3456, word: "goodbye"}
                            ]
                          )

      spy = sinon.spy()

      Word.getNouns (result) -> spy(result); done(); null

      expect(spy).have.been.calledWith [
        {id: 1234, word: "hello"},
        {id: 2345, word: "foo"},
        {id: 3456, word: "goodbye"}
      ]

For some reason I am getting a done() was called twice error when I run mocha. If I run the callback outside of process.nextTick().

Your test is calling expect(spy).have.been.calledWith before the spy was called via spy(result).

I assume that when the expect fails, done is called for the first time (the test is done and failed). In the next tick, done is called again from your getNouns callback.

You don't need the spy to check the value passed to getNouns callback, you can do the assert immediately in the callback.

sinon.stub(Word._wordnik, 'randomWords').yields(null, [
                          {id: 1234, word: "hello"},
                          {id: 2345, word: "foo"},
                          {id: 3456, word: "goodbye"}
                        ]
                      )

Word.getNouns (result) ->
  expect(result).to.deep.equal [
    {id: 1234, word: "hello"},
    {id: 2345, word: "foo"},
    {id: 3456, word: "goodbye"}
  ]
  done()