sinon.replace vs sinon.stub 只是为了替换返回值?

Tak*_*ARA 5 javascript sinon

使用 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)

dee*_*wan 9

我很少看到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

  • 虽然简单性声明是公平的,但重复使用相同的存根是一种反模式,如果您在测试之间没有正确清理,可能会导致不稳定的测试,这就是我们引入“fake”和“replace”方法的原因。这也是注入“fake”的唯一方法。 (2认同)