Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
875 views
in Technique[技术] by (71.8m points)

javascript - sinon.replace vs sinon.stub just to replace return value?

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);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...