Sinon: Mock an internal class object and pass the arguments to constructor

42 views Asked by At

Here is the sample snippet:

const Key = require('./key');
const KeyService = require('./key-service');
module.exports.getData = (request, response, next) => {
  ....
  const params = {};
  const key = new Key('default', '12345');
//How should pass a mock 'key' object in to 'create' method below ?
  return KeyService.create('someKeyId', key, params) //'key' is key instance, from above
    .then((response1) => {
    return response1.getById(id)
      .then((response2) => {
        response.status(200);
      })
    })catch((error) => {
    })
  ....
}

-----------------
class Key {
  constructor(id, value) {
    //Few assert statement to check whethere id & value is not empty.
    this._id = id;
    this._value = value;
  }
}

-------------------------
class KeyService {
  static create(id, value, params) {
    //returns KeyService object within promise
  }
  
  getById(keyId, correlationId) {
    //returns response within Promise
  }
}

Here, I am mocking the getData method. But while doing this, I am struggling to mock the Key object (i.e. the constructor by passing the arguments). How to mock an internal class (i.e. Key) and pass along with the arguments in constructor via sinon. And, later mock all nested promise.

I tried by using Sinon.createStubInstance, but it seems its not working. (I cannot use spying as I dont want to do some introspect). Any pointers would be appreciated so that I can build on top of that. Thanks.

0

There are 0 answers