【问题标题】:How to stub ES5 class constructor?如何存根 ES5 类构造函数?
【发布时间】:2019-04-09 02:09:42
【问题描述】:

我找不到存根 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();

预期输出:存根

当前输出:你好

【问题讨论】:

  • 这个帖子可能对你有帮助 github.com/sinonjs/sinon/issues/1892
  • Object.setPrototypeOf(A, sinon.stub().callsFake(function() { console.log('I am Super Stub!'); } ));似乎不起作用

标签: javascript typescript sinon


【解决方案1】:

helloinstance 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

【讨论】:

  • 看来我的方法不正确,我试图存根使用实例属性的第三方库“google-spreadsheet”,我通过使用proxyquire 覆盖库来解决它。但是你回答了我的问题,说在创建实例之前存根实例属性是不可能的。
猜你喜欢
  • 2019-09-21
  • 2022-01-18
  • 1970-01-01
  • 2011-11-24
  • 2015-06-20
  • 2017-03-27
  • 2018-06-18
  • 1970-01-01
  • 2019-03-11
相关资源
最近更新 更多