Metaman
Metaman

Reputation: 421

Stubbing a private function that returns a promise

I'm completely new to frontend testing and I'm having some trouble progressing with a particular test. I'm using Mocha, Sinon and Chai.

Basically I have some private functions that I would like to test. I don't want to expose them to the API so I'm trying to mock the functions instead using Sinon.

One of the private functions returns a promise and has roughly the following structure:

myPrivateFunc(arg1, arg2).done(function(x) {
  if (x.length > 0) {
    // do something
  } else {
    // call some other private function 
  }
});

I tried to stub this by doing something like this:

sinon.stub(object, 'myPrivateFunction').withArgs(args1, args2);

When I call the public function in my test, the private function is correctly called, but of course eventually fails:

TypeError: Cannot read property 'done' of undefined

I've tried messing around with .returns() but I'm not really sure what I'm doing at all.

Could anybody point me in the right direction? I've looked at other similar questions and couldn't really find a suitable answer.

Upvotes: 0

Views: 1345

Answers (1)

trincot
trincot

Reputation: 350034

You can indeed use .returns to specify the value that the sub should return. That value should have a done property.

Possibly you are using a jQuery or similar deferred object (e.g. returned by $.ajax) which exposes a done method (which is not standard for promises: then would be a better option). If that is indeed what you use, you could create a dummy deferred object for the stub's return value:

sinon.stub(object, 'myPrivateFunction')
     .withArgs(args1, args2)
     .returns($.Deferred().resolve([1,2,3])); 

Replace [1,2,3] with whatever value you want x to be.

Otherwise you can always create a plain object that has the done method:

sinon.stub(object, 'myPrivateFunction')
     .withArgs(args1, args2)
     .returns( { done: x => [1,2,3] } ); 

Upvotes: 1

Related Questions