Eoley
Eoley

Reputation: 61

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;
    }
}

Upvotes: 6

Views: 1671

Answers (1)

Hizir
Hizir

Reputation: 214

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.

Upvotes: 2

Related Questions