类型错误: 试图包装已包装的内容



我的代码:

before(function _before() {
this.myObject = new MyObject();
});
it('should', sinon.test(function() {
const stubLog = sinon.stub(this.myObject.log, 'warn');
}));
it('should 2', sinon.test(function() {
const stubLog = sinon.stub(this.myObject.log, 'warn');
}));

西农版本:1.17.6

为什么我在应该 2 测试中得到错误TypeError: Attempted to wrap warn which is already wrapped?我应该手动恢复stubLog吗?我想sinon.test()会为我做这件事。也许我做错了什么?

欢迎任何评论。谢谢

您收到错误是因为您需要在创建另一个存根之前重置存根。您可以使用 stub.reset(( 或 stub.restore(( 来执行此操作,最好在 beforeEach 中。

https://sinonjs.org/releases/latest/stubs/

您是否尝试过在沙盒中使用this.stub()而不是sinon.stub()

const stubLog = this.stub(this.myObject.log, 'warn');

从官方文档中,举个例子:

it('should do something', sinonTest(function(){
var spy1 = this.spy(myFunc);
var spy2 = this.spy(myOtherFunc);
myFunc(1);
myFunc(2);
assert(spy1.calledWith(1));
assert(spy1.calledWith(2));
}));

一旦用sinon.test()包裹,该函数将访问自身内部的this指针,并使用它来存根/监视其他函数。

像这样使用它应该会自动为您恢复存根。

最新更新