原型上的 Sinon 存根,检查调用它的实际实例的值
Sinon stub on prototype, check value of actual instance it is called on
我有一个关于原型和方法的 sinon 存根...
stub = sinon.stub(MyType.prototype, 'someFunction');
MyType
在 属性 中有一些值,具体取决于它是哪个实例。让我们调用 属性 identifier
.
我需要检查两件事...
使用正确的参数调用了 someFunction
。
expect(stub).to.have.been.calledWith('Some Parameter');
(这按预期工作)。
调用函数的实例的identifier
是正确的。 MyType
有很多实例,我需要检查是否在正确的实例上调用了函数。
我可以做第一个检查。但我不知道如何(或者即使)我可以进行第二次检查。
这可能吗?
谢谢
是的,这是可能的。
您可以使用 sinon.assert.calledOn
, spy.calledOn
, spyCall.thisValue
, or spy.thisValues
检查呼叫的 this
值:
import * as sinon from 'sinon';
class MyType {
constructor(id) {
this.identifier = id;
}
someFunction(arg) { }
}
test('someFunction', () => {
const stub = sinon.stub(MyType.prototype, 'someFunction');
const one = new MyType("oneId");
const two = new MyType("twoId");
one.someFunction('firstArg');
two.someFunction('secondArg');
sinon.assert.calledWith(stub.firstCall, 'firstArg'); // SUCCESS
sinon.assert.calledOn(stub.firstCall, one); // SUCCESS
expect(stub.firstCall.thisValue.identifier).to.equal('oneId'); // SUCCESS
sinon.assert.calledWith(stub.secondCall, 'secondArg'); // SUCCESS
sinon.assert.calledOn(stub.secondCall, two); // SUCCESS
expect(stub.secondCall.thisValue.identifier).to.equal('twoId'); // SUCCESS
});
我有一个关于原型和方法的 sinon 存根...
stub = sinon.stub(MyType.prototype, 'someFunction');
MyType
在 属性 中有一些值,具体取决于它是哪个实例。让我们调用 属性 identifier
.
我需要检查两件事...
使用正确的参数调用了
someFunction
。expect(stub).to.have.been.calledWith('Some Parameter');
(这按预期工作)。调用函数的实例的
identifier
是正确的。MyType
有很多实例,我需要检查是否在正确的实例上调用了函数。
我可以做第一个检查。但我不知道如何(或者即使)我可以进行第二次检查。
这可能吗?
谢谢
是的,这是可能的。
您可以使用 sinon.assert.calledOn
, spy.calledOn
, spyCall.thisValue
, or spy.thisValues
检查呼叫的 this
值:
import * as sinon from 'sinon';
class MyType {
constructor(id) {
this.identifier = id;
}
someFunction(arg) { }
}
test('someFunction', () => {
const stub = sinon.stub(MyType.prototype, 'someFunction');
const one = new MyType("oneId");
const two = new MyType("twoId");
one.someFunction('firstArg');
two.someFunction('secondArg');
sinon.assert.calledWith(stub.firstCall, 'firstArg'); // SUCCESS
sinon.assert.calledOn(stub.firstCall, one); // SUCCESS
expect(stub.firstCall.thisValue.identifier).to.equal('oneId'); // SUCCESS
sinon.assert.calledWith(stub.secondCall, 'secondArg'); // SUCCESS
sinon.assert.calledOn(stub.secondCall, two); // SUCCESS
expect(stub.secondCall.thisValue.identifier).to.equal('twoId'); // SUCCESS
});