简体   繁体   中英

How can I test sequence of function calls by Sinon.js?

How can I test sequence of function calls by Sinon.js?

For example i have three (3) handlers in object, and want define sequence of handler calls. Is there any possibilities for this?

http://sinonjs.org/docs/

sinon.assert.callOrder(spy1, spy2, ...)

Passes if the provided spies where called in the specified order.

For people who run into this looking for a way to define stubs with a specified behaviour on a call sequence. There is no direct way (as far as I've seen) to say: "This stub will be called X times, on the 1st call it will take parameter a and return b on the 2nd call it will take parameter c and return d ..." and so on.

The closest I found to this behaviour is:

  const expectation = sinon.stub()
            .exactly(N)
            .onCall(0)
            .returns(b)
            .onCall(1)
            .returns(d)
            // ...
            ;
   // Test that will end up calling the stub
   // expectation.callCount should be N
   // expectation.getCalls().map(call => call.args) should be [ a, b, ... ]

This way we can return specific values on each call in the sequence and then assert that the calls were made with the parameters we expected.

As Gajus mentioned callOrder() is no longer available and you can use callBefore() , calledAfter() , calledImmediatelyBefore() and calledImmediatelyAfter() .

I found most convenient to assert sequential calls of one spy by getting all calls using spy.getCalls() and do assert.deepEqual() for call arguments.

Example - Assert order of console.log() calls.

// func to test
function testee() {
  console.log(`a`)
  console.log(`b`)
  console.log(`c`)
}

In your test case

const expected = [`a`, `b`, `c`]
const consoleSpy = spy(console, 'log')

testee()

const result = consoleSpy.getCalls().map(({ args }) => args[0])

assert.deepEqual(result, expected)

There is also a sinon-chai plugin.

https://www.npmjs.com/package/sinon-chai-in-order

expect(spy).inOrder.to.have.been.calledWith(1)
                   .subsequently.calledWith(2)
                   .subsequently.calledWith(3);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM