协助在 class 中存根函数
Assistance stubbing a function inside class
我正在尝试存根 Enmap 的设置方法。这是我的功能(在我的 Queue
class 内):
// save queue for persistence
save() {
enmap.set('queue', this._queue);
}
这是我到目前为止所做的:
var enmapStub;
beforeEach(() => {
enmapStub = sinon.stub(new enmap(), 'set');
});
afterEach(() => {
enmapStub.restore();
});
然后在我的测试中使用它:
describe('#save', () => {
it("calls enmap.set", () => {
new Queue({ queueName: 'test', queue: [1,2,3] }).save();
expect(enmapStub).to.have.been.calledOnce;
});
});
未调用enmapStub导致测试失败?
我刚开始使用 sinon
和一般的模拟,所以我确定我错过了一步或其他什么。有谁知道我错在哪里?
我确定了这个问题,因为我想模拟另一个 class 的 set 方法(Enmap
)我需要像这样存根 Enmap 的原型:
this.enmapStub;
beforeEach(() => {
this.enmapStub = sinon.stub(enmap.prototype, 'set');
});
afterEach(() => {
this.enmapStub.restore();
});
存根原型而不是 Enmap 的实例效果更好。
我正在尝试存根 Enmap 的设置方法。这是我的功能(在我的 Queue
class 内):
// save queue for persistence
save() {
enmap.set('queue', this._queue);
}
这是我到目前为止所做的:
var enmapStub;
beforeEach(() => {
enmapStub = sinon.stub(new enmap(), 'set');
});
afterEach(() => {
enmapStub.restore();
});
然后在我的测试中使用它:
describe('#save', () => {
it("calls enmap.set", () => {
new Queue({ queueName: 'test', queue: [1,2,3] }).save();
expect(enmapStub).to.have.been.calledOnce;
});
});
未调用enmapStub导致测试失败?
我刚开始使用 sinon
和一般的模拟,所以我确定我错过了一步或其他什么。有谁知道我错在哪里?
我确定了这个问题,因为我想模拟另一个 class 的 set 方法(Enmap
)我需要像这样存根 Enmap 的原型:
this.enmapStub;
beforeEach(() => {
this.enmapStub = sinon.stub(enmap.prototype, 'set');
});
afterEach(() => {
this.enmapStub.restore();
});
存根原型而不是 Enmap 的实例效果更好。