1
votes

I am hoping someone will be able to help me out with a small issue. I am trying to stub out an undefined property that lives inside a function and return a known value, I am trying this with a simple test case:

var self = this;


self.test = function() {
  return person.myId();
};


if (typeof module !== "undefined" && module.hasOwnProperty("exports")) {
  module.exports = self;
}


return self;

what I have tried to do is:

it('Basic stub test', function() {
  sinon.stub(code, 'person.myId').return("1234");
  assert(code.test(), "1234");
});

I had hoped the above would stub any calls made to person.myId(), however, I just get any error saying: Cannot stub non-existent own property person.myId.

We use our own software that handles dependency injection (e.g. during runtime in our software person is made available) but we are attempting to write isolated unit tests outside of the software, hence the necessity for stubbing out the missing dependencies.

Has anyone attempted this kind of thing before? Am I trying to do something that isn't possible?

Thank you for any help/support anyone can provide.

Sam

1
how is person defined in the code? - Alexey Kucherenko
person is a object that is injected during run time using custom software and made available to the script. - Samuel O'Donnell
is it possible to add to the code above or no? - Alexey Kucherenko

1 Answers

-1
votes

I'm not sure what kind of magic the dependency injection software does, so here is a middle ground answer.

It's less than ideal because it tends to be a code smell if you're changing the code you want to test, although it fits your specific question.

I'm also assuming you're using something like mocha that provides the before & afterEach functions.


var sandbox = sinon.createSandbox();

before(function () {
  var person = {
    myId: () => console.log('myId no op'),
  };

  code.person = person;
}

it('Basic stub test', function() {
  sandbox.stub(code.person, 'myId').returns('1234');
  assert(code.test(), '1234');
});

afterEach(function () {
  sandbox.restore();
});

Documentation Link: http://sinonjs.org/releases/v4.1.3/sandbox/

(Although the use of sandbox isn't strictly required here)