简体   繁体   中英

How to stub ES5 class constructor?

I can't find a proper way to stub es5 class object methods. It would also work if I could just return fake object/class when new A() is called.

What I have tried

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();

Expected output: stubbed

Current output: hello

hello is an instance property ...

...so a new function gets created and added as the hello property of each new instance.

So mocking it requires an instance:

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'
});

If hello is changed to be a prototype method it can be stubbed for all instances:

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'
});

Note that the prototype method approach is equivalent to this ES6 code:

class A {
  hello() {
    console.log("hello");
  }
}

...which seems like it might be how you intended to define hello .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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