通过参数验证对自身执行 Fake 的 CallOrder

Doing CallOrder of Fake on itself with argument validation

如何在 sinon.js 中使用参数验证对假货进行调用顺序验证? 这是同一个假货,用不同的参数多次调用...... 类似下面

        let someFake = sinon.fake();
        someFake(1);
        someFake(2);
        someFake(3);
        sinon.assert.callOrder(someFake.calledWith(1), someFake.calledWith(2), 
        someFake.calledWith(3));

您基本上使用了错误的 API 作为工作,所以难怪您没有得到预期的结果 :) 如果您查看 callOrder you will see that the signature is using spy1, spy2, .., which indicates that it is meant to be used by more than one spy. A fake is implementation wise also a Spy, so all bits of the Spy API also applies to a Fake. From the docs 的文档:

The created fake Function, with or without behavior has the same API as a sinon.spy

一个有点令人困惑的旁白是,文档经常使用术语“假”来表示任何假对象或函数,而不是使用 sinon.fake API 创建的函数,不过,在这种特殊情况下,这不应该成为问题。

关于您最初的问题,Spy API 从 Sinon 1.0 开始就已经为您解答了。您使用 getCall(n) 到 return 第 n 次调用。文档中有很多交互式示例,但基本上您只需这样做:

// dumbed down version of https://runkit.com/fatso83/Whosebug-66192966

const fake = sinon.fake();
fake(1);
fake(20);
fake(300);

sinon.assert.calledThrice(fake);       
assertEquals(1, fake.getCall(0).args[0])
assertEquals(20, fake.secondCall.args[0])
assertEquals(300, fake.lastCall.args[0])

function assertEquals(arg1,arg2){
  if(arg1 !== arg2) { 
     throw new Error(`Expected ${arg1} to equal ${arg2}`); 
  }
  console.log(`${arg1} equal ${arg2}: OK`)
}
<script src="https://cdn.jsdelivr.net/npm/sinon@latest/pkg/sinon.js"></script>