我找不到一个正确的方法来存根es5类对象方法。如果我可以在调用new A()
时返回假对象/类,它也会起作用。
我试过了什么
sinon.stub(A, 'hello').callsFake(() => console.log("stubbed"))
sinon.stub(A.prototype, 'hello').callsFake(() => console.log("stubbed"))
sinon.stub(A, 'constructor').callsFake(() => {hello: ()=>console.log("stubbed")})
function A () {
this.hello = function() {
console.log("hello");
}
}
new A().hello();
预期输出:存根
当前输出:你好
hello
是一个instance property ...
...所以创建一个新函数并添加为每个新实例的hello
属性。
所以嘲笑它需要一个实例:
const sinon = require('sinon');
function A () {
this.hello = function() { // <= hello is an instance property
console.log("hello");
}
}
it('should stub hello', () => {
const a = new A(); // <= create an instance
sinon.stub(a, 'hello').callsFake(() => console.log("stubbed")); // <= stub the instance property
a.hello(); // <= logs 'stubbed'
});
如果将hello
更改为prototype method,则可以为所有实例存根:
const sinon = require('sinon');
function A () {
}
A.prototype.hello = function() { // <= hello is a prototype method
console.log("hello");
}
it('should stub hello', () => {
sinon.stub(A.prototype, 'hello').callsFake(() => console.log("stubbed")); // <= stub the prototype method
new A().hello(); // <= logs 'stubbed'
});
请注意,原型方法方法等同于此ES6代码:
class A {
hello() {
console.log("hello");
}
}
...这似乎可能是你打算如何定义hello
。