Add spy.getCallByArgs(args..) and spy.getCallByAllArgs(args..) #198

Closed
alFReD-NSH opened this Issue Nov 2, 2012 · 5 comments

Projects

None yet

3 participants

@alFReD-NSH
Contributor

spy.getCallsByArgs(args..) will find the calls that it's first arguments matches specified arguments(partial matching, kinda like calledWithArgs).
spy.getCallsByAllArgs(args..) will find the calls that all it's arguments matches specified arguments(matching all like calledWithExactlyArgs).

In my tests my spy get's called more than a few times with variable arguments and a callback(which I don't have access to) and I can't rely on the calling sequence. To check their arguments I have to do the following:

spy.args.forEach(function (callArgs) {
  if (callArgs[0] === 'call0param1') {
    assert.equals(callArgs[1], 'call0param2', 'Wrong arguments.');
    someMoreChecking(callArgs);
  } else if (callArgs[0] === 'call1param1') {
    assert.equals(callArgs[2], 'call1param2', 'Wrong arguments.');
  } else ...
});

Or in another place:

spy.args.some(function (callArgs, index) {
  if (callArgs[0] === 'call0param1') {
    checkTheCall(spy.getCall(index););
    return true;
  }
});

Now if I had those methods, the first code will change to:

var firstCall = spy.getCallsByArgs('call0param1')[0];
assert(firstCall.calledWith('call0param2'));
someMoreChecking(firstCall);
var secondCall = spy.getCallsByArgs('call1param1')[0];
assert(secondCall.calledWith('call1param1'));

Or the second will change to the following:

var theCall = spy.getCallsByArgs('call0param1');
checkTheCall(theCall);

Bonus points if it throws when didn't find any matching call.

@mantoni
Member
mantoni commented Nov 2, 2012

If your test does not depend on the spied functions being invoked, you can use stubs instead which implement this feature. See withArgs here: http://sinonjs.org/docs/#stubs-api

Otherwise, I would rather add the withArgs feature to spies for consistency.
@cjohansen what do you think?

@alFReD-NSH
Contributor

@mantoni Thought withArgs only works for the methods for the stub interface, not the ones inherited from the spy interface(eg .args). But it does do what I want. I just use the stubs for now.

But for consistency implementing withArgs is a better solution.

@cjohansen
Contributor

I guess adding withArgs to spies would make sense. @mantoni do you foresee any bad things happening if we do that?

@mantoni
Member
mantoni commented Nov 6, 2012

Hm. I would limit the functionality of spy.withArgs to just filtering calls. I don't see any problems with that.

@mantoni
Member
mantoni commented May 22, 2013

This was released a couple of month ago. Closing issue.

@mantoni mantoni closed this May 22, 2013
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment