sinon.replace vs sinon.stub 只是为了替换 return 值?
sinon.replace vs sinon.stub just to replace return value?
使用 sinon 时,我只想替换函数的 return 值,不需要其他信息,例如它被调用了多少次。哪一个比较好?
sinon.replace(Component.prototype, 'getValue', () => 123);
const myStub = sinon.stub(Component.prototype, 'getValue');
myStub.return(123);
我很少看到 sinon.replace
在很多项目中被使用。例如,使用 stub
的优点是您可以多次修改 return 值。
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
})
同时,对于replace
,根据Sinon文档,您只能使用一次。
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.
例如:
sinon.replace(Component.prototype, 'getValue', function () {
return 123;
});
sinon.replace(Component.prototype, 'getValue', function () { // this will return error
return 456;
});
会return错误
TypeError: Attempted to replace getValue which is already replaced
你可能可以通过用 stub
替换函数来实现与 sinon.replace
stub 相同的功能
getValueStub = sinon.stub();
sinon.replace(Component.prototype, 'getValue', getValueStub);
getValueStub.returns(123);
getValueStub.returns(456);
不过,由于简单,我更喜欢使用 sinon.stub
。
参考:
https://sinonjs.org/releases/v7.2.2/sandbox/#sandboxreplaceobject-property-replacement
使用 sinon 时,我只想替换函数的 return 值,不需要其他信息,例如它被调用了多少次。哪一个比较好?
sinon.replace(Component.prototype, 'getValue', () => 123);
const myStub = sinon.stub(Component.prototype, 'getValue');
myStub.return(123);
我很少看到 sinon.replace
在很多项目中被使用。例如,使用 stub
的优点是您可以多次修改 return 值。
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
})
同时,对于replace
,根据Sinon文档,您只能使用一次。
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.
例如:
sinon.replace(Component.prototype, 'getValue', function () {
return 123;
});
sinon.replace(Component.prototype, 'getValue', function () { // this will return error
return 456;
});
会return错误
TypeError: Attempted to replace getValue which is already replaced
你可能可以通过用 stub
替换函数来实现与sinon.replace
stub 相同的功能
getValueStub = sinon.stub();
sinon.replace(Component.prototype, 'getValue', getValueStub);
getValueStub.returns(123);
getValueStub.returns(456);
不过,由于简单,我更喜欢使用 sinon.stub
。
参考:
https://sinonjs.org/releases/v7.2.2/sandbox/#sandboxreplaceobject-property-replacement