Read more

Jasmine: Adding custom matchers

Dominik Schöler
May 02, 2018Software engineer at makandra GmbH

Definition

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() {
      return {
        compare(actualValue, ...matcherArguments) {
           // Do some computations here ...
         
           // Return whether the actualValue matches the expectation
           return {pass: true}
         }
      }
    }
  })
})

Usage

expect(actualValue).toBeAnything(...matcherArguments)
Illustration money motivation

Opscomplete powered by makandra brand

Save money by migrating from AWS to our fully managed hosting in Germany.

  • Trusted by over 100 customers
  • Ready to use with Ruby, Node.js, PHP
  • Proactive management by operations experts
Read more Show archive.org snapshot

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 Show archive.org snapshot , 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.

Matcher libraries

There are some libraries that provide additional matchers to Jasmine:

Posted by Dominik Schöler to makandra dev (2018-05-02 12:19)