最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin6浏览0评论

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);

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);
Share Improve this question edited Jan 22, 2019 at 13:45 Federico klez Culloca 27.1k17 gold badges59 silver badges100 bronze badges asked Jan 21, 2019 at 5:31 Takuya HARATakuya HARA 6571 gold badge6 silver badges21 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 16

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/releases/v7.2.2/sandbox/#sandboxreplaceobject-property-replacement

发布评论

评论列表(0)

  1. 暂无评论