UNPKG

jest-extended

Version:
61 lines (60 loc) 3.09 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.toHaveBeenCalledAfter = toHaveBeenCalledAfter; const utils_1 = require("../utils"); function toHaveBeenCalledAfter(actual, expected, failIfNoFirstInvocation = 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; if ((0, utils_1.isJestMockOrSpy)(actual)) { // @ts-expect-error isJestMockOrSpy provides the type check firstInvocationCallOrder = actual.mock.invocationCallOrder; secondInvocationCallOrder = expected.mock.invocationCallOrder; pass = predicate(firstInvocationCallOrder, secondInvocationCallOrder, failIfNoFirstInvocation); } return { pass, message: () => pass ? matcherHint('.not.toHaveBeenCalledAfter') + '\n\n' + 'Expected first mock to not have been called after, invocationCallOrder:\n' + ` ${printExpected(firstInvocationCallOrder)}\n` + 'Received second mock with invocationCallOrder:\n' + ` ${printReceived(secondInvocationCallOrder)}` : matcherHint('.toHaveBeenCalledAfter') + '\n\n' + 'Expected first mock to have been called after, invocationCallOrder:\n' + ` ${printExpected(firstInvocationCallOrder)}\n` + 'Received second mock with invocationCallOrder:\n' + ` ${printReceived(secondInvocationCallOrder)}`, }; } const smallest = (ns) => ns.reduce((acc, n) => (acc < n ? acc : n)); const predicate = (firstInvocationCallOrder, secondInvocationCallOrder, failIfNoFirstInvocation) => { if (firstInvocationCallOrder.length === 0) return !failIfNoFirstInvocation; if (secondInvocationCallOrder.length === 0) return false; const firstSmallest = smallest(firstInvocationCallOrder); const secondSmallest = smallest(secondInvocationCallOrder); return firstSmallest > secondSmallest; }; const mockCheckFailMessage = (utils, value, isReceivedValue) => () => { const valueKind = isReceivedValue ? 'Received' : 'Expected'; const valueKindPrintFunc = isReceivedValue ? utils.printReceived : utils.printExpected; return (utils.matcherHint('.toHaveBeenCalledAfter') + '\n\n' + `Matcher error: ${valueKindPrintFunc(valueKind.toLowerCase())} must be a mock or spy function` + '\n\n' + utils.printWithType(valueKind, value, valueKindPrintFunc)); };