Skip to content
Advertisement

How to add custom matchers to jasmine globally?

I’d need a replacement for the jasmine.addMatchers function gone in version 1.3. The current API allows to add matchers to a describe block, but I’d prefer to be able to use my matchers everywhere without adding them again and again.

Is there a global way to add own matchers to jasmine 3.1.0?

Advertisement

Answer

https://github.com/JamieMason/add-matchers can be used to write matchers which work in all versions of Jasmine, as well as Jest.

var addMatchers = require('add-matchers');

addMatchers({
  // matcher with 0 arguments
  toBeEvenNumber: function(received) {
    // received : 4
    return received % 2 === 0;
  },
  // matcher with 1 argument
  toBeOfType: function(type, received) {
    // type     : 'Object'
    // received : {}
    return Object.prototype.toString.call(received) === '[object ' + type + ']';
  },
  // matcher with many arguments
  toContainItems: function(arg1, arg2, arg3, received) {
    // arg1     : 2
    // arg2     : 15
    // arg3     : 100
    // received : [100, 14, 15, 2]
    return (
      received.indexOf(arg1) !== -1 &&
      received.indexOf(arg2) !== -1 &&
      received.indexOf(arg3) !== -1
    );
  }
});
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement