Posted over 2 years ago. Visible to the public. Repeats. Linked content.

Jasmine: Adding custom matchers


A matcher is a function that returns an object with a compare key. Usually it is registered with beforeEach:

beforeEach -> jasmine.addMatchers # Example matcher toBeAnything: -> compare: (actualValue, matcherArguments...) -> # Do some computations here ... # Return whether the actualValue matches the expectation pass: true



When a matcher is invoked, Jasmine will call its compare() function with the actualValue, followed by any arguments passed to the matcher. It should process them to determine whether the expectation is fulfilled, and return an object with a pass: true/false pair.

As you can see in the linked article, the object returned by compare() supports a few more options, e.g. setting a helpful failure message.

Definition location

I suggest putting generic matchers into spec/javascripts/support/matchers/, and specific matchers into the file where they're needed.

Note: There are collections of Jasmine matchers you could reuse. As always, avoid including huge libraries when you're only using a single feature of them. You might just copy the matchers you need over to your project.

Once an application no longer requires constant development, it needs periodic maintenance for stable and secure operation. makandra offers monthly maintenance contracts that let you focus on your business while we make sure the lights stay on.

Owner of this card:

Dominik Schöler
Last edit:
over 2 years ago
by Arne Hartherz
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Dominik Schöler to makandra dev
This website uses short-lived cookies to improve usability.
Accept or learn more