Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jest - Externalise extended expect matchers

I have. node.js-TypeScript applciation and Jest for testing. Using this reference https://jestjs.io/docs/expect#expectextendmatchers I have some extended expect matchers in my test classes. Exactly like the example below. I have a lot of common extends in several different test classes. Is there a way to externalise/group these extended matchers and use in the test classes by importing them?

Example:

expect.extend({
  async toBeDivisibleByExternalValue(received) {
    const externalValue = await getExternalValueFromRemoteSource();
    const pass = received % externalValue == 0;
    if (pass) {
      return {
        message: () =>
          `expected ${received} not to be divisible by ${externalValue}`,
        pass: true,
      };
    } else {
      return {
        message: () =>
          `expected ${received} to be divisible by ${externalValue}`,
        pass: false,
      };
    }
  },
});

test('is divisible by external value', async () => {
  await expect(100).toBeDivisibleByExternalValue();
  await expect(101).not.toBeDivisibleByExternalValue();
});

My jest.d.ts:

export {};
declare global {
  namespace jest {
    interface Matchers<R> {
      hasTestData(): R;
    }
}
like image 951
Eoley Avatar asked Nov 07 '22 02:11

Eoley


1 Answers

For common extended expects I use the following logic;

ExtendedExpects.ts:

declare global {
    namespace jest {
        interface Matchers<R> {
            toBeDivisibleByExternalValue(): R;
        }
    }
}
export function toBeDivisibleByExternalValue(received:any): jest.CustomMatcherResult {
    const externalValue = await getExternalValueFromRemoteSource();
    const pass = received % externalValue == 0;
    if (pass) {
      return {
        message: () =>
          `expected ${received} not to be divisible by ${externalValue}`,
        pass: true,
      };
    } else {
      return {
        message: () =>
          `expected ${received} to be divisible by ${externalValue}`,
        pass: false,
      };
    }
}

You defined the common method, now how to consume it;

Your test class will look like,

import { toBeDivisibleByExternalValue } from "../ExtendedExpects";

expect.extend({
   toBeDivisibleByExternalValue
});

test('is divisible by external value', async () => {
  await expect(100).toBeDivisibleByExternalValue();
  await expect(101).not.toBeDivisibleByExternalValue();
});

You do not need jest.d.ts anymore.

like image 99
Hizir Avatar answered Nov 11 '22 04:11

Hizir