且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用Mocha和sinon测试异步功能

更新时间:2023-01-16 19:58:50

如果您知道总是在最后设置一条特定的消息,则可以在发出该消息时指示Sinon调用函数.该函数可以是Mocha用于异步测试的回调函数:

If you know that a particular message is always set last, you can instruct Sinon to call a function when that message is emitted. That function can be Mocha's callback function for asynchronous tests:

describe("myFun", function() {
  // Extend timeout and "slow test" values.
  this.timeout(3000).slow(10000);

  const fakeSocket = { emit: sinon.stub() }

  it('should emit a certain final message', done => {
    fakeSocket.emit.withArgs('third', 'hello Mars? Venus? I dunno...')
                   .callsFake(() => done());
    myFun(fakeSocket);
  });
});

因此,如果使用参数'third', 'hello Mars?...'调用socket.emit(),则Sinon将调用一个函数,该函数调用done回调,向Mocha表示测试已完成.

So if socket.emit() is called with arguments 'third', 'hello Mars?...', Sinon will call a function that calls the done callback, signalling to Mocha that the test has completed.

由于某种原因未发出该特定消息时,done永远不会被调用,并且测试将超时(3秒后),这表明测试失败或花费了更多时间比预期的要好.

When, for some reason, that particular message isn't emitted, done never gets called and the test will time out (after 3s), which is an indication that either the test has failed, or it took more time than expected.

如果您不知道socket.emit()的第一个参数是最后一条消息,仅消息本身,则测试将变为:

If you don't know what the first argument to socket.emit() is going to be for the last message, only the message itself, the test becomes this:

it('should emit a certain final message', done => {
  fakeSocket.emit.callsFake((name, msg) => {
    if (msg === 'hello Mars? Venus? I dunno...') {
      done();
    }
  });
  myFun(fakeSocket);
})