如何用process.nextTick进行testing

我正在使用摩卡来testing一些Node.js代码,并希望使用process.nextTick()来调用方法的callback。

代码

  @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()被称为两次错误,当我运行摩卡。 如果我在process.nextTick()之外运行callback。

你的testing是调用expect(spy).have.been.calledWith之前,间谍被称为spy(result)

我假设当期望失败时,第一次调用done (testing完成并失败)。 在下一个勾号中, donegetNounscallback中被再次调用。

您不需要间谍来检查传递给getNounscallback的值,您可以立即在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()