How to add custom matchers to jasmine globally?

1.1k views Asked by At

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?

3

There are 3 answers

0
Jamie Mason On BEST 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
    );
  }
});
5
Andrew Eisenberg On

Note that I have not tried this in jasmine 3.1, but this is how I am doing the same in jasmine 2.8:

Place this in any code block that gets run before your tests:

jasmine.getEnv().beforeEach(() => {
  jasmine.addMatchers({
    toBeAwesome(util, customEqualityTesters) { ... }
  })
});
0
Lucass On

With jasmine-core version 3.8 (possibly already with 3.1) the answer by Andrew Eisenberg no longer works. Therefore I have created a beforeAll() outside my tests (= outside of all describe-blocks), which is thereby executed before all tests.

If you work with Angular you can place it in src/test.ts.

Inside the beforeAll() I simply call jasmine.addMatchers(myCustomMatcher):

beforeAll(() => jasmine.addMatchers(myCustomMatcher));