Jest: Adding custom matchers : Cannot read property "addMatchers" of undefined

Created on 4 Sep 2017  路  3Comments  路  Source: facebook/jest

On Jest 20.0.4, when I try to add custom matchers in my setup.js file, I get the following error :

   TypeError: Cannot read property 'addMatchers' of undefined

      at Object.addMatchers (node_modules/jest-runtime/build/index.js:720:39)
      at Object.<anonymous> (jest/setup.js:73:6)
          at <anonymous>
      at process._tickCallback (internal/process/next_tick.js:188:7)

My file looks like this :

jest.addMatchers({
  toPartiallyEqual(received, object, keysToReject) {
    if(Object.keys(received).length !== Object.keys(object).length) {
      return {
        message: () => (`expected ${received} to be partially equal to ${object}`),
        pass: false,
      };
    }

    let match = true;
    Object.keys(received).forEach(key => {
      if(match === false) return;
      if(keysToReject.indexOf(key) >= 0) return;
      if(received.hasOwnProperty(key) === false) return;

      if(received[key] !== object[key]) {
        match = false;
      }
    });

    if(match) {
      return {
        message: () => (`expected ${received} to be partially equal to ${object}`),
        pass: true,
      };
    } else {
      return {
        message: () => (`expected ${received} to be partially equal to ${object}`),
        pass: false,
      };
    }
  }
});

Most helpful comment

You can only add matchers in the setupTestFrameworkScriptFile config option.

All 3 comments

You can only add matchers in the setupTestFrameworkScriptFile config option.

In jest v22, you can define custom matchers in individual test suites and use them. I am doing it right now.

I actually ran into a problem moving those definitions out of the test suite and into the setup file.

Was this page helpful?
0 / 5 - 0 ratings