UNPKG

2.12 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3exports.calledWithFn = void 0;
4const Matchers_1 = require("./Matchers");
5function isJestAsymmetricMatcher(obj) {
6 return !!obj && typeof obj === 'object' && 'asymmetricMatch' in obj && typeof obj.asymmetricMatch === 'function';
7}
8const checkCalledWith = (calledWithStack, actualArgs, fallbackMockImplementation) => {
9 const calledWithInstance = calledWithStack.find((instance) => instance.args.every((matcher, i) => {
10 if (matcher instanceof Matchers_1.Matcher) {
11 return matcher.asymmetricMatch(actualArgs[i]);
12 }
13 if (isJestAsymmetricMatcher(matcher)) {
14 return matcher.asymmetricMatch(actualArgs[i]);
15 }
16 return actualArgs[i] === matcher;
17 }));
18 // @ts-ignore cannot return undefined, but this will fail the test if there is an expectation which is what we want
19 return calledWithInstance
20 ? calledWithInstance.calledWithFn(...actualArgs)
21 : fallbackMockImplementation && fallbackMockImplementation(...actualArgs);
22};
23const calledWithFn = ({ fallbackMockImplementation, } = {}) => {
24 const fn = jest.fn(fallbackMockImplementation);
25 let calledWithStack = [];
26 fn.calledWith = (...args) => {
27 // We create new function to delegate any interactions (mockReturnValue etc.) to for this set of args.
28 // If that set of args is matched, we just call that jest.fn() for the result.
29 const calledWithFn = jest.fn(fallbackMockImplementation);
30 const mockImplementation = fn.getMockImplementation();
31 if (!mockImplementation || mockImplementation === fallbackMockImplementation) {
32 // Our original function gets a mock implementation which handles the matching
33 fn.mockImplementation((...args) => checkCalledWith(calledWithStack, args, fallbackMockImplementation));
34 calledWithStack = [];
35 }
36 calledWithStack.unshift({ args, calledWithFn });
37 return calledWithFn;
38 };
39 return fn;
40};
41exports.calledWithFn = calledWithFn;
42exports.default = exports.calledWithFn;