在流程中编写规范:如何在 mocha 中存根方法?
Writing specs in flow: how to stub a method in mocha?
ClassA有只读属性b
,b
有方法c
,在A#methodF
,有一个声明:
const v = await this.b.c();
在 A#methodF
的规范中,我想存根 c
:
a.b.c = sinon.stub().resolves({myDesiredResult})
(其中 a
是 A
的实例)
但 flow check
给出:
Cannot assign sinon.stub().resolves(...) to
a.b.c because property c
is not writable.
问题:如何让c
return得到我想要的结果?
您的问题是您没有正确使用 sinon.stub。当您真的想将存根分配给新变量时,您正试图将 a.b.c 设置为新值(存根)。 sinon.stub 的语法是 (docs):
var stub = sinon.stub(object, "method");
所以在你的情况下:
var cStub = sinon.stub(a.b, "c").resolves({myDesiredResult})
ClassA有只读属性b
,b
有方法c
,在A#methodF
,有一个声明:
const v = await this.b.c();
在 A#methodF
的规范中,我想存根 c
:
a.b.c = sinon.stub().resolves({myDesiredResult})
(其中 a
是 A
的实例)
但 flow check
给出:
Cannot assign sinon.stub().resolves(...) to a.b.c because property c is not writable.
问题:如何让c
return得到我想要的结果?
您的问题是您没有正确使用 sinon.stub。当您真的想将存根分配给新变量时,您正试图将 a.b.c 设置为新值(存根)。 sinon.stub 的语法是 (docs):
var stub = sinon.stub(object, "method");
所以在你的情况下:
var cStub = sinon.stub(a.b, "c").resolves({myDesiredResult})