Mocking JavaScript constructor with Sinon.JS

You can either create a namespace or create a stub instance using sinon.createStubInstance (this will not invoke the constructor).

Creating a namespace:

const namespace = {
  Service: require('./service')
};

describe('Service', function() {
  it('getData', function() {
    sinon.stub(namespace, 'Service').returns(0);
    console.log(new namespace.Service()); // Service {}
  });
});

Creating a stub instance:

let Service = require('./service');

describe('Service', function() {
  it('getData', function() {
    let stub = sinon.createStubInstance(Service);
    console.log(stub); // Service {}
  });
});

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)