create-spies-group.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. import {createSpy} from './create-spy.js';
  2. /**
  3. * Группа позволяет создавать шпионов
  4. * и управлять ими как одним.
  5. */
  6. export class SpiesGroup {
  7. /**
  8. * Constructor.
  9. */
  10. constructor() {
  11. this.spies = [];
  12. }
  13. /**
  14. * Создает шпиона для отдельной функции
  15. * или метода объекта и добавляет его в группу.
  16. *
  17. * @param {Function|object} [target]
  18. * @param {Function|string} [methodNameOrImpl]
  19. * @param {Function} [customImplForMethod]
  20. * @returns {Function}
  21. */
  22. on(target, methodNameOrImpl, customImplForMethod) {
  23. const spy = createSpy(target, methodNameOrImpl, customImplForMethod);
  24. this.spies.push(spy);
  25. return spy;
  26. }
  27. /**
  28. * Восстановление всех оригинальных методов объектов,
  29. * для которых были созданы шпионы в этой группе,
  30. * и сброс истории вызовов для всех шпионов в группе.
  31. * Очищает внутренний список шпионов.
  32. *
  33. * @returns {this}
  34. */
  35. restore() {
  36. this.spies.forEach(spy => spy.restore());
  37. this.spies = [];
  38. return this;
  39. }
  40. }
  41. /**
  42. * Создание группы шпионов.
  43. *
  44. * @returns {SpiesGroup}
  45. */
  46. export function createSpiesGroup() {
  47. return new SpiesGroup();
  48. }