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

耗尽温柔 提交于 2020-12-23 10:55:56

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!