Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

jasmine

I have reviewed Jasmine's documentation of the toHaveBeenCalledWith matcher in order to understand whether it's possible to pass in a regular expression for an argument, if that argument is expected to be a string. Unfortunately, this is unsupported functionality. There's also an issue open on github requesting this functionality.

I've dug a bit into the codebase, and I see how it might be possible to implement this inside the existing matcher. I think it would be more appropriate to implement it as a separate matcher though, so that the abstraction is captured individually.

In the meantime, what might be a good workaround?

like image 433
zealoushacker Avatar asked Feb 12 '13 20:02

zealoushacker


1 Answers

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.

like image 117
zealoushacker Avatar answered Oct 04 '22 20:10

zealoushacker