called-in-order.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. "use strict";
  2. var every = require("./prototypes/array").every;
  3. /**
  4. * @private
  5. */
  6. function hasCallsLeft(callMap, spy) {
  7. if (callMap[spy.id] === undefined) {
  8. callMap[spy.id] = 0;
  9. }
  10. return callMap[spy.id] < spy.callCount;
  11. }
  12. /**
  13. * @private
  14. */
  15. function checkAdjacentCalls(callMap, spy, index, spies) {
  16. var calledBeforeNext = true;
  17. if (index !== spies.length - 1) {
  18. calledBeforeNext = spy.calledBefore(spies[index + 1]);
  19. }
  20. if (hasCallsLeft(callMap, spy) && calledBeforeNext) {
  21. callMap[spy.id] += 1;
  22. return true;
  23. }
  24. return false;
  25. }
  26. /**
  27. * A Sinon proxy object (fake, spy, stub)
  28. *
  29. * @typedef {object} SinonProxy
  30. * @property {Function} calledBefore - A method that determines if this proxy was called before another one
  31. * @property {string} id - Some id
  32. * @property {number} callCount - Number of times this proxy has been called
  33. */
  34. /**
  35. * Returns true when the spies have been called in the order they were supplied in
  36. *
  37. * @param {SinonProxy[] | SinonProxy} spies An array of proxies, or several proxies as arguments
  38. * @returns {boolean} true when spies are called in order, false otherwise
  39. */
  40. function calledInOrder(spies) {
  41. var callMap = {};
  42. // eslint-disable-next-line no-underscore-dangle
  43. var _spies = arguments.length > 1 ? arguments : spies;
  44. return every(_spies, checkAdjacentCalls.bind(null, callMap));
  45. }
  46. module.exports = calledInOrder;