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
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])
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With