I rarely see sinon.replace
being used in many projects. The advantage of using stub
is you can modify the return value many times for example.
let getValueStub;
before(function() {
getValueStub = sinon.stub(Component.prototype, 'getValue');
})
after(function() {
sinon.restore();
})
it('test case A if return value is 123', function() {
getValueStub.returns(123);
// do expectation
})
it('test case B if return value is 234', function() {
getValueStub.returns(234);
// do expectation
})
Meanwhile, for replace
, based on Sinon documentation, you can use it only one time.
sandbox.replace(object, property, replacement);
Replaces property on object with replacement argument. Attempts to
replace an already replaced value cause an exception.
replacement can be any value, including spies, stubs and fakes.
For example:
sinon.replace(Component.prototype, 'getValue', function () {
return 123;
});
sinon.replace(Component.prototype, 'getValue', function () { // this will return error
return 456;
});
it will return error
TypeError: Attempted to replace getValue which is already replaced
You probably can achieve the same thing like stub with sinon.replace
by replacing the function with stub
getValueStub = sinon.stub();
sinon.replace(Component.prototype, 'getValue', getValueStub);
getValueStub.returns(123);
getValueStub.returns(456);
Still, I prefer use sinon.stub
due to simplicity.
Reference:
https://sinonjs.org/releases/v7.2.2/sandbox/#sandboxreplaceobject-property-replacement
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…