Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I stub and spy at the same time

So I'm testing a function that calls another function, that returns a promise, SUT looks like this:

fn($modal) -> 
    modalInstance = $modal.open({
       controller: 'myCtrl'
       size: 'lg'
     })

    modalInstance.result.then(updateData)

now If I need to test it I could start with something like this:

it 'when modal called, results get updated with right data', ->

   $modal = {
      open: sinon.stub().returns({ 
          result: $q.when([1, 2, 3]) 
      })
   }

   fn($modal)

and then check if the updatedData is equal to [1,2,3]

but I'd like to also make sure that $modal.open has been called and correct parameters been passed into it. How do I do that?

I need to not only stub the method but also spy on it, should I mock entire $modal? Can you help me with the right syntax?

When I do something like this:

mMk  = sinon.mock($modal)
mMk.expects('open')

Sinon yells at me: TypeError: Attempted to wrap open which is already stubbed

like image 987
iLemming Avatar asked Feb 10 '23 20:02

iLemming


1 Answers

Stubs in Sinon support the full spy API, so you can do something like this:

// override $modal
$modal = {
    open: sinon.stub().returns({
        result: $q.when([1, 2, 3])
    });
};

fn($modal);
expect($modal.open).toHaveBeenCalledWith(...);

Note that if $modal is an injectable service, it may be cleaner to just stub the open method rather than override the entire $modal.

// override $modal.open
sinon.stub($modal, 'open').returns({
    result: $q.when([1, 2, 3])
});
like image 87
Igor Raush Avatar answered Feb 12 '23 10:02

Igor Raush