spy_matchers.js 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161
  1. 'use strict';
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();
  6. var _jestMatcherUtils = require('jest-matcher-utils');
  7. var _jasmine_utils = require('./jasmine_utils');
  8. var _utils = require('./utils');
  9. const CALL_PRINT_LIMIT = 3; /**
  10. * Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
  11. *
  12. * This source code is licensed under the MIT license found in the
  13. * LICENSE file in the root directory of this source tree.
  14. *
  15. *
  16. */
  17. const LAST_CALL_PRINT_LIMIT = 1;
  18. const createToBeCalledMatcher = matcherName => (received, expected) => {
  19. (0, _jestMatcherUtils.ensureNoExpected)(expected, matcherName);
  20. ensureMock(received, matcherName);
  21. const receivedIsSpy = isSpy(received);
  22. const type = receivedIsSpy ? 'spy' : 'mock function';
  23. const receivedName = receivedIsSpy ? 'spy' : received.getMockName();
  24. const count = receivedIsSpy ? received.calls.count() : received.mock.calls.length;
  25. const calls = receivedIsSpy ? received.calls.all().map(x => x.args) : received.mock.calls;
  26. const pass = count > 0;
  27. const message = pass ? () => (0, _jestMatcherUtils.matcherHint)('.not' + matcherName, receivedName, '') + '\n\n' + `Expected ${type} not to be called ` + formatReceivedCalls(calls, CALL_PRINT_LIMIT, { sameSentence: true }) : () => (0, _jestMatcherUtils.matcherHint)(matcherName, receivedName, '') + '\n\n' + `Expected ${type} to have been called.`;
  28. return { message, pass };
  29. };
  30. const createToBeCalledWithMatcher = matcherName => function (received) {
  31. for (var _len = arguments.length, expected = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  32. expected[_key - 1] = arguments[_key];
  33. }
  34. ensureMock(received, matcherName);
  35. const receivedIsSpy = isSpy(received);
  36. const type = receivedIsSpy ? 'spy' : 'mock function';
  37. const receivedName = receivedIsSpy ? 'spy' : received.getMockName();
  38. const calls = receivedIsSpy ? received.calls.all().map(x => x.args) : received.mock.calls;
  39. var _partition = (0, _utils.partition)(calls, call => (0, _jasmine_utils.equals)(call, expected, [_utils.iterableEquality])),
  40. _partition2 = _slicedToArray(_partition, 2);
  41. const match = _partition2[0],
  42. fail = _partition2[1];
  43. const pass = match.length > 0;
  44. const message = pass ? () => (0, _jestMatcherUtils.matcherHint)('.not' + matcherName, receivedName) + '\n\n' + `Expected ${type} not to have been called with:\n` + ` ${(0, _jestMatcherUtils.printExpected)(expected)}` : () => (0, _jestMatcherUtils.matcherHint)(matcherName, receivedName) + '\n\n' + `Expected ${type} to have been called with:\n` + formatMismatchedCalls(fail, expected, CALL_PRINT_LIMIT);
  45. return { message, pass };
  46. };
  47. const createLastCalledWithMatcher = matcherName => function (received) {
  48. for (var _len2 = arguments.length, expected = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
  49. expected[_key2 - 1] = arguments[_key2];
  50. }
  51. ensureMock(received, matcherName);
  52. const receivedIsSpy = isSpy(received);
  53. const type = receivedIsSpy ? 'spy' : 'mock function';
  54. const receivedName = receivedIsSpy ? 'spy' : received.getMockName();
  55. const calls = receivedIsSpy ? received.calls.all().map(x => x.args) : received.mock.calls;
  56. const pass = (0, _jasmine_utils.equals)(calls[calls.length - 1], expected, [_utils.iterableEquality]);
  57. const message = pass ? () => (0, _jestMatcherUtils.matcherHint)('.not' + matcherName, receivedName) + '\n\n' + `Expected ${type} to not have been last called with:\n` + ` ${(0, _jestMatcherUtils.printExpected)(expected)}` : () => (0, _jestMatcherUtils.matcherHint)(matcherName, receivedName) + '\n\n' + `Expected ${type} to have been last called with:\n` + formatMismatchedCalls(calls, expected, LAST_CALL_PRINT_LIMIT);
  58. return { message, pass };
  59. };
  60. const spyMatchers = {
  61. lastCalledWith: createLastCalledWithMatcher('.lastCalledWith'),
  62. toBeCalled: createToBeCalledMatcher('.toBeCalled'),
  63. toBeCalledWith: createToBeCalledWithMatcher('.toBeCalledWith'),
  64. toHaveBeenCalled: createToBeCalledMatcher('.toHaveBeenCalled'),
  65. toHaveBeenCalledTimes(received, expected) {
  66. const matcherName = '.toHaveBeenCalledTimes';
  67. (0, _jestMatcherUtils.ensureExpectedIsNumber)(expected, matcherName);
  68. ensureMock(received, matcherName);
  69. const receivedIsSpy = isSpy(received);
  70. const type = receivedIsSpy ? 'spy' : 'mock function';
  71. const receivedName = receivedIsSpy ? 'spy' : received.getMockName();
  72. const count = receivedIsSpy ? received.calls.count() : received.mock.calls.length;
  73. const pass = count === expected;
  74. const message = pass ? () => (0, _jestMatcherUtils.matcherHint)('.not' + matcherName, receivedName, String(expected)) + `\n\n` + `Expected ${type} not to be called ` + `${(0, _jestMatcherUtils.EXPECTED_COLOR)((0, _jestMatcherUtils.pluralize)('time', expected))}, but it was` + ` called exactly ${(0, _jestMatcherUtils.RECEIVED_COLOR)((0, _jestMatcherUtils.pluralize)('time', count))}.` : () => (0, _jestMatcherUtils.matcherHint)(matcherName, receivedName, String(expected)) + '\n\n' + `Expected ${type} to have been called ` + `${(0, _jestMatcherUtils.EXPECTED_COLOR)((0, _jestMatcherUtils.pluralize)('time', expected))},` + ` but it was called ${(0, _jestMatcherUtils.RECEIVED_COLOR)((0, _jestMatcherUtils.pluralize)('time', count))}.`;
  75. return { message, pass };
  76. },
  77. toHaveBeenCalledWith: createToBeCalledWithMatcher('.toHaveBeenCalledWith'),
  78. toHaveBeenLastCalledWith: createLastCalledWithMatcher('.toHaveBeenLastCalledWith')
  79. };
  80. const isSpy = spy => spy.calls && typeof spy.calls.count === 'function';
  81. const ensureMock = (mockOrSpy, matcherName) => {
  82. if (!mockOrSpy || (mockOrSpy.calls === undefined || mockOrSpy.calls.all === undefined) && mockOrSpy._isMockFunction !== true) {
  83. throw new Error((0, _jestMatcherUtils.matcherHint)('[.not]' + matcherName, 'jest.fn()', '') + '\n\n' + `${(0, _jestMatcherUtils.RECEIVED_COLOR)('jest.fn()')} value must be a mock function ` + `or spy.\n` + (0, _jestMatcherUtils.printWithType)('Received', mockOrSpy, _jestMatcherUtils.printReceived));
  84. }
  85. };
  86. const getPrintedCalls = (calls, limit, sep, fn) => {
  87. const result = [];
  88. let i = calls.length;
  89. while (--i >= 0 && --limit >= 0) {
  90. result.push(fn(calls[i]));
  91. }
  92. return result.join(sep);
  93. };
  94. const formatReceivedCalls = (calls, limit, options) => {
  95. if (calls.length) {
  96. const but = options && options.sameSentence ? 'but' : 'But';
  97. const count = calls.length - limit;
  98. const printedCalls = getPrintedCalls(calls, limit, ', ', _jestMatcherUtils.printReceived);
  99. return `${but} it was ${options && options.isLast ? 'last ' : ''}called ` + `with:\n ` + printedCalls + (count > 0 ? '\nand ' + (0, _jestMatcherUtils.RECEIVED_COLOR)((0, _jestMatcherUtils.pluralize)('more call', count)) + '.' : '');
  100. } else {
  101. return `But it was ${(0, _jestMatcherUtils.RECEIVED_COLOR)('not called')}.`;
  102. }
  103. };
  104. const formatMismatchedCalls = (calls, expected, limit) => {
  105. if (calls.length) {
  106. return getPrintedCalls(calls, limit, '\n\n', formatMismatchedArgs.bind(null, expected));
  107. } else {
  108. return ` ${(0, _jestMatcherUtils.printExpected)(expected)}\n` + `But it was ${(0, _jestMatcherUtils.RECEIVED_COLOR)('not called')}.`;
  109. }
  110. };
  111. const formatMismatchedArgs = (expected, received) => {
  112. const length = Math.max(expected.length, received.length);
  113. const printedArgs = [];
  114. for (let i = 0; i < length; i++) {
  115. if (!(0, _jasmine_utils.equals)(expected[i], received[i], [_utils.iterableEquality])) {
  116. printedArgs.push(` ${(0, _jestMatcherUtils.printExpected)(expected[i])} as argument ${i + 1}, ` + `but it was called with ${(0, _jestMatcherUtils.printReceived)(received[i])}.`);
  117. } else if (i >= expected.length) {
  118. printedArgs.push(` Did not expect argument ${i + 1} ` + `but it was called with ${(0, _jestMatcherUtils.printReceived)(received[i])}.`);
  119. }
  120. }
  121. return printedArgs.join('\n');
  122. };
  123. exports.default = spyMatchers;