jest-extended
Version:
Additional Jest matchers
59 lines (58 loc) • 3.03 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.toHaveBeenCalledBefore = toHaveBeenCalledBefore;
const utils_1 = require("../utils");
function toHaveBeenCalledBefore(actual, expected, failIfNoSecondInvocation = true) {
// @ts-expect-error OK to have implicit any for this.utils
const { printReceived, printExpected, matcherHint } = this.utils;
if (!(0, utils_1.isJestMockOrSpy)(actual)) {
// @ts-expect-error OK to have implicit any for this.utils
return { pass: false, message: mockCheckFailMessage(this.utils, actual, true) };
}
if (!(0, utils_1.isJestMockOrSpy)(expected)) {
// @ts-expect-error OK to have implicit any for this.utils
return { pass: false, message: mockCheckFailMessage(this.utils, expected, false) };
}
let pass = false;
let firstInvocationCallOrder = null;
let secondInvocationCallOrder = null;
// @ts-expect-error isJestMockOrSpy provides the type check
firstInvocationCallOrder = actual.mock.invocationCallOrder;
secondInvocationCallOrder = expected.mock.invocationCallOrder;
pass = predicate(firstInvocationCallOrder, secondInvocationCallOrder, failIfNoSecondInvocation);
return {
pass,
message: () => pass
? matcherHint('.not.toHaveBeenCalledBefore') +
'\n\n' +
'Expected first mock to not have been called before, invocationCallOrder:\n' +
` ${printExpected(firstInvocationCallOrder)}\n` +
'Received second mock with invocationCallOrder:\n' +
` ${printReceived(secondInvocationCallOrder)}`
: matcherHint('.toHaveBeenCalledBefore') +
'\n\n' +
'Expected first mock to have been called before, invocationCallOrder:\n' +
` ${printExpected(firstInvocationCallOrder)}\n` +
'Received second mock with invocationCallOrder:\n' +
` ${printReceived(secondInvocationCallOrder)}`,
};
}
const mockCheckFailMessage = (utils, value, isReceivedValue) => () => {
const valueKind = isReceivedValue ? 'Received' : 'Expected';
const valueKindPrintFunc = isReceivedValue ? utils.printReceived : utils.printExpected;
return (utils.matcherHint('.toHaveBeenCalledBefore') +
'\n\n' +
`Matcher error: ${valueKindPrintFunc(valueKind.toLowerCase())} must be a mock or spy function` +
'\n\n' +
utils.printWithType(valueKind, value, valueKindPrintFunc));
};
const smallest = (ns) => ns.reduce((acc, n) => (acc < n ? acc : n));
const predicate = (firstInvocationCallOrder, secondInvocationCallOrder, failIfNoSecondInvocation) => {
if (firstInvocationCallOrder.length === 0)
return false;
if (secondInvocationCallOrder.length === 0)
return !failIfNoSecondInvocation;
const firstSmallest = smallest(firstInvocationCallOrder);
const secondSmallest = smallest(secondInvocationCallOrder);
return firstSmallest < secondSmallest;
};