create-sandbox.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. import {createSpy} from './create-spy.js';
  2. /**
  3. * Песочница позволяет создавать шпионов
  4. * и управлять ими как единым целым.
  5. */
  6. export class Sandbox {
  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. * @returns {this}
  33. */
  34. restore() {
  35. this.spies.forEach(spy => spy.restore());
  36. this.spies = [];
  37. return this;
  38. }
  39. }
  40. /**
  41. * Создание песочницы.
  42. *
  43. * @returns {Sandbox}
  44. */
  45. export function createSandbox() {
  46. return new Sandbox();
  47. }