2

我正在使用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"}
      ]

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

4

1 回答 1

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()
于 2013-07-19T15:43:10.980 回答