extend

Bun

Symbol

Expect.extend

extend<M>(matchers: ExpectExtendMatchers<M>): void

Register new custom matchers.

@param matchers

An object containing the matchers to register, where each key is the matcher name, and its value the implementation function. The function must satisfy: (actualValue, ...matcherInstantiationArguments) => { pass: true|false, message: () => string }

expect.extend({
    toBeWithinRange(actual, min, max) {
        if (typeof actual !== 'number' || typeof min !== 'number' || typeof max !== 'number')
            throw new Error('Invalid usage');
        const pass = actual >= min && actual <= max;
        return {
            pass: pass,
            message: () => `expected ${this.utils.printReceived(actual)} ` +
                (pass ? `not to be`: `to be`) + ` within range ${this.utils.printExpected(`${min} .. ${max}`)}`,
        };
    },
});

test('some test', () => {
  expect(50).toBeWithinRange(0, 100); // will pass
  expect(50).toBeWithinRange(100, 200); // will fail
  expect(50).toBe(expect.toBeWithinRange(0, 100)); // will pass
  expect(50).toBe(expect.not.toBeWithinRange(100, 200)); // will pass
});

Referenced types

type ExpectExtendMatchers<M> = { [K in keyof M]: k extends keyof CustomMatchersDetected ? CustomMatcher<unknown, Parameters<CustomMatchersDetected[k]>> : CustomMatcher<unknown, any[]> }

If the types has been defined through declaration merging, enforce it. Otherwise enforce the generic custom matcher signature.