问题
When using sinon I just want to replace my function's return value and don't need other infos like how many time it was called. Which one of them is better?
sinon.replace(Component.prototype, 'getValue', () => 123);
const myStub = sinon.stub(Component.prototype, 'getValue');
myStub.return(123);
回答1:
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
来源:https://stackoverflow.com/questions/54283946/sinon-replace-vs-sinon-stub-just-to-replace-return-value