繁体   English   中英

如何存根ES5类构造函数?

[英]How to stub ES5 class constructor?

我找不到对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实例属性 ...

...因此创建了一个新函数并将其添加为每个新实例的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更改为原型方法,则可以在所有实例中将其存根:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM