toHaveBeenCalledWith: equal vs. identical arguments

3,464 views
Skip to first unread message

tbus...@eclipsesource.com

unread,
Feb 7, 2014, 8:42:56 AM2/7/14
to jasmi...@googlegroups.com
Hi there.

The following code would pass in jasmine:
      var spy = jasmine.createSpy();
      spy( {} );
      expect( spy ).toHaveBeenCalledWith( {} );

Which I find somewhat dangerous, since the two objects not the same instance.
The follwing fails:

      expect( spy.mostRecentCall.args[ 0 ] ).toBe( {} );

Is there a way to use toHaveBeenCalledWith to check for identity? I know I can use the above, but then I might get into trouble if there are multiple calls.

Greetings,
Tim

Ben Loveridge

unread,
Feb 8, 2014, 11:27:19 PM2/8/14
to jasmi...@googlegroups.com
Tim,

You can write a custom matcher that does this.

Below is some sample code that demonstrates how this might can be done. This example would need to be improved upon to be a good general purpose tool -- if you decide to go this route I suggest taking a look at the source for the toHaveBeenCalledWith matcher and adapt it as necessary because it will capture a lot more of the edge cases than the sample below, which only works when testing for the first argument and continues to process all calls even if it's already found a match; I meant this to be clean and short, not a full robust solution.

  beforeEach(function() {
    jasmine.getEnv().currentSpec.addMatchers({
      toHaveBeenCalledWithExactly: function(expected) {
        var self = this, matched = false;
        this.actual.calls.forEach(function(call, i) {
          if(self.actual.argsForCall[i][0] === expected) {
            matched = true;
          }
        });
        return matched;
      }
    });
  });
  it('should be able to use object identity when comparing function arguments', function() {
    var a = {}, b = {};
    var spy = jasmine.createSpy();
    spy(a);
    expect(spy).toHaveBeenCalledWith(b); // true
    expect(spy).toHaveBeenCalledWithExactly(a); // true
    expect(spy).toHaveBeenCalledWithExactly(b); // false
  });


Cheers,
- Ben


--
You received this message because you are subscribed to the Google Groups "Jasmine" group.
To unsubscribe from this group and stop receiving emails from it, send an email to jasmine-js+...@googlegroups.com.
To post to this group, send email to jasmi...@googlegroups.com.
Visit this group at http://groups.google.com/group/jasmine-js.
For more options, visit https://groups.google.com/groups/opt_out.

Reply all
Reply to author
Forward
0 new messages