如何存根 ES5 class 构造函数?
How to stub ES5 class constructor?
我找不到存根 es5 class 对象方法的正确方法。如果在调用 new A()
时我可以 return 伪造 object/class,它也会起作用。
我试过的
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
。
我找不到存根 es5 class 对象方法的正确方法。如果在调用 new A()
时我可以 return 伪造 object/class,它也会起作用。
我试过的
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
。