gpt4 book ai didi

javascript - 协助在类中 stub 函数

转载 作者:行者123 更新时间:2023-11-28 21:36:25 25 4
gpt4 key购买 nike

我正在尝试对 Enmap 的设置方法进行 stub 。这是我的函数(在我的 Queue 类中):

// 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 和一般的模拟,所以我确定我错过了一步或其他什么。有谁知道我哪里出错了?

最佳答案

我确定了这个问题,因为我想模拟另一个类 (Enmap) 的 set 方法,我需要像这样 stub Enmap 的原型(prototype):

this.enmapStub;
beforeEach(() => {
this.enmapStub = sinon.stub(enmap.prototype, 'set');
});

afterEach(() => {
this.enmapStub.restore();
});

stub 原型(prototype)而不是 Enmap 的实例效果更好。

关于javascript - 协助在类中 stub 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58344222/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com