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;
    }
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With