I am trying to add a custom matcher to Jest in Typescript. This works fine, but I can\'t get Typescript to recognize the extended Matchers.
myMatcher.ts
A simple way is:
customMatchers.ts
declare global {
namespace jest {
interface Matchers {
// add any of your custom matchers here
toBeDivisibleBy: (argument: number) => {};
}
}
}
// this will extend the expect with a custom matcher
expect.extend({
toBeDivisibleBy(received: number, argument: number) {
const pass = received % argument === 0;
if (pass) {
return {
message: () => `expected ${received} not to be divisible by ${argument}`,
pass: true
};
} else {
return {
message: () => `expected ${received} to be divisible by ${argument}`,
pass: false
};
}
}
});
my.spec.ts
import "path/to/customMatchers";
test('even and odd numbers', () => {
expect(100).toBeDivisibleBy(2);
expect(101).not.toBeDivisibleBy(2);
});