如何使用process.nextTick进行测试

时间:2012-07-18 13:29:37

标签: node.js testing asynchronous mocha sinon

我正在使用Mocha来测试一些Node.js代码,并希望使用process.nextTick()来调用方法的回调。

守则

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

测试

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"}
      ]

出于某种原因,当我运行mocha时,我得到done()被调用了两次错误。如果我在process.nextTick()之外运行回调。

1 个答案:

答案 0 :(得分:1)

在通过expect(spy).have.been.calledWith调用间谍之前,您的测试正在调用spy(result)

我假设当期望失败时,第一次调用done(测试完成并失败)。在下一个勾选中,done将再次从getNouns回调中调用{。}}。

您不需要间谍检查传递给getNouns回调的值,您可以在回调中立即执行断言。

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()