- 赛农版本:v2.0.0-pre.2
- 环境:Windows 10
- 您正在使用的其他库:Typescript、babel、mocha、chai
您预计会发生什么?
我希望能够在类中添加一个箭头函数。
实际发生了什么
我不能 stub 箭头函数,但是,我可以 stub 类原型(prototype)函数。
FAILED TESTS:
ExampleClass tests
× should stub thisDoesntWork arrow function
Chrome 52.0.2743 (Windows 10 0.0.0)
TypeError: Attempted to wrap undefined property thisDoesntWork as function
at wrapMethod (webpack:///~/sinon/pkg/sinon.js:3138:0 <- test-bundler.js:7377:21)
at Object.stub (webpack:///~/sinon/pkg/sinon.js:2472:0 <- test-bundler.js:6711:12)
at Context.<anonymous> (webpack:///src/stores/sinon.test.ts:22:51 <- test-bundler.js:96197:72)
如何重现
export class ExampleClass {
thisWorks() {
return 0;
}
thisDoesntWork = () => {
return 0;
}
}
describe("ExampleClass tests", () => {
it("should stub thisWorks function", () => {
let stubFunctionA = sinon.stub(ExampleClass.prototype, "thisWorks");
});
it("should stub thisDoesntWork arrow function", () => {
let stubFunctionB = sinon.stub(ExampleClass, "thisDoesntWork");
});
});
最佳答案
我从未使用过 sinon
,但在他们的文档中,它为 sinon.stub
函数声明:
Replaces object.method with a stub function
如果您查看 ExampleClass
的已编译 js 代码:
var ExampleClass = (function () {
function ExampleClass() {
this.thisDoesntWork = function () {
return 0;
};
}
ExampleClass.prototype.thisWorks = function () {
return 0;
};
return ExampleClass;
}());
然后你会看到 ExampleClass.prototype.thisWorks
被定义了,但是没有 ExampleClass.thisDoesntWork
定义,甚至没有 ExampleClass.prototype.thisDoesntWork
.
thisDoesntWork
方法仅在构造函数中添加(箭头函数不是真正的类方法,它们只是具有函数类型的类成员)。
我怀疑这会起作用:
describe("ExampleClass tests", () => {
it("should stub thisDoesntWork arrow function", () => {
let stubFunctionB = sinon.stub(new ExampleClass(), "thisDoesntWork");
});
});
关于javascript - 无法使用 Sinon 在类中 stub 箭头函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39301935/