使用 sinon 时,我只想替换函数的返回值,不需要其他信息,例如调用了多少次。其中哪一个更好?
sinon.replace(Component.prototype, 'getValue', () => 123);
Run Code Online (Sandbox Code Playgroud)
const myStub = sinon.stub(Component.prototype, 'getValue');
myStub.return(123);
Run Code Online (Sandbox Code Playgroud)
我很少看到sinon.replace在许多项目中使用。使用的好处stub是你可以多次修改返回值。
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
})
Run Code Online (Sandbox Code Playgroud)
同时,对于replace,根据Sinon文档,您只能使用一次。
沙盒.替换(对象,属性,替换);
用替换参数替换对象上的属性。尝试替换已替换的值会导致异常。
替换可以是任何值,包括间谍、存根和赝品。
例如:
sinon.replace(Component.prototype, 'getValue', function () {
return 123;
});
sinon.replace(Component.prototype, 'getValue', function () { // this will return error
return 456;
});
Run Code Online (Sandbox Code Playgroud)
它会返回错误
TypeError: Attempted to replace getValue which is already replaced
Run Code Online (Sandbox Code Playgroud)
您可能可以sinon.replace通过将函数替换为stub 来实现与 stub 相同的功能
getValueStub = sinon.stub();
sinon.replace(Component.prototype, 'getValue', getValueStub);
getValueStub.returns(123);
getValueStub.returns(456);
Run Code Online (Sandbox Code Playgroud)
不过,sinon.stub由于简单,我更喜欢使用。
参考:
https://sinonjs.org/releases/v7.2.2/sandbox/#sandboxreplaceobject-property-replacement
| 归档时间: |
|
| 查看次数: |
6335 次 |
| 最近记录: |