Is it possible to use Jasmine's toHaveBeenCalledWith matcher with a regular expression?

Solution 1:

After doing some digging, I've discovered that Jasmine spy objects have a calls property, which in turn has a mostRecent() function. This function also has a child property args, which returns an array of call arguments.

Thus, one may use the following sequence to perform a regexp match on call arguments, when one wants to check that the string arguments match a specific regular expression:

var mySpy = jasmine.createSpy('foo');
mySpy("bar", "baz");
expect(mySpy.calls.mostRecent().args[0]).toMatch(/bar/);
expect(mySpy.calls.mostRecent().args[1]).toMatch(/baz/);

Pretty straightforward.

Solution 2:

As of Jasmine 2.2, you can use jasmine.stringMatching:

var mySpy = jasmine.createSpy('foo');
mySpy('bar', 'baz');
expect(mySpy).toHaveBeenCalledWith(
  jasmine.stringMatching(/bar/),
  jasmine.stringMatching(/baz/)
);

Solution 3:

In Jasmine 2.0 the signature changed a bit. Here it would be:

var mySpy = jasmine.createSpy('foo');
mySpy("bar", "baz");
expect(mySpy.calls.mostRecent().args[0]).toMatch(/bar/);
expect(mySpy.calls.mostRecent().args[1]).toMatch(/baz/);

And the Documentation for Jasmine 1.3 has moved.

Solution 4:

Alternatively, if you are spying on a method on an object:

spyOn(obj, 'method');
obj.method('bar', 'baz');
expect(obj.method.argsForCall[0][0]).toMatch(/bar/);
expect(obj.method.argsForCall[0][1]).toMatch(/baz/);