【问题标题】:How to test with process.nextTick如何使用 process.nextTick 进行测试
【发布时间】:2012-07-17 13:25:51
【问题描述】:

我正在使用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() 之外运行回调。

【问题讨论】:

  • 没有完全理解最后一句话——process.nextTick() 之外会发生什么?

标签: node.js testing asynchronous mocha.js sinon


【解决方案1】:

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

我假设当期望失败时,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()

【讨论】:

    猜你喜欢
    • 2015-02-25
    • 2010-09-25
    • 2016-11-12
    • 1970-01-01
    • 1970-01-01
    • 2017-08-27
    • 2018-02-15
    • 2018-11-09
    • 1970-01-01
    相关资源
    最近更新 更多