我如何测试Sinon.js函数调用的顺序

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

本文关键字:js Sinon 函数调用 顺序 测试 何测试      更新时间:2023-09-26

如何测试Sinon.js的函数调用顺序?

例如,我在对象中有三(3)个处理程序,并且想要定义处理程序调用的序列。这有可能吗?

http://sinonjs.org/docs/

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

如果按指定顺序调用所提供的间谍,则传递。

对于遇到这种情况的人来说,寻找一种方法来定义具有调用序列上指定行为的存根。没有直接的方法(据我所见)说:"这个存根将被调用X次,在第一次调用时,它将接受参数a并返回b;在第二次调用时,它将接受参数c并返回d……"等等。

我发现最接近这种行为的是:

  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, ... ]

通过这种方式,我们可以在序列中的每次调用中返回特定的值,然后断言调用是使用我们期望的形参进行的。

正如Gajus提到的,callOrder()不再可用,您可以使用callBefore(), calledAfter(), calledImmediatelyBefore()calledImmediatelyAfter()

我发现通过使用spy.getCalls()获取所有调用并使用assert.deepEqual()获取调用参数来断言一个间谍的顺序调用是最方便的。

示例-断言console.log()调用的顺序。

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

在您的测试用例

const expected = [`a`, `b`, `c`]
const consoleSpy = spy(console, 'log')
testee()
const result = consoleSpy.getCalls().map(({ args }) => args[0])
assert.deepEqual(result, expected)

还有一个sinon-chai插件

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

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