Browse Source

refactor: reformat code

e22m4u 1 day ago
parent
commit
d624aff4e7
4 changed files with 71 additions and 226 deletions
  1. 5 6
      dist/cjs/index.cjs
  2. 5 8
      src/chai/chai-spies.js
  3. 37 71
      src/create-sandbox.spec.js
  4. 24 141
      src/create-spy.spec.js

+ 5 - 6
dist/cjs/index.cjs

@@ -135,20 +135,20 @@ function chaiSpies(chai, _) {
     return n + "th";
     return n + "th";
   }
   }
   __name(generateOrdinalNumber, "generateOrdinalNumber");
   __name(generateOrdinalNumber, "generateOrdinalNumber");
-  function assertWith() {
+  function assertWith(...expArgs) {
     new Assertion(this._obj).to.be.spy;
     new Assertion(this._obj).to.be.spy;
-    const expArgs = [].slice.call(arguments, 0), spy = this._obj, calls = spy.calls, always = _.flag(this, "spy always"), nthCall = _.flag(this, "spy nth call with");
+    const spy = this._obj, calls = spy.calls, always = _.flag(this, "spy always"), nthCall = _.flag(this, "spy nth call with");
     if (always) {
     if (always) {
       const passed = numberOfCallsWith(spy, expArgs);
       const passed = numberOfCallsWith(spy, expArgs);
       this.assert(
       this.assert(
-        arguments.length ? calls.length && passed === calls.length : calls.length === 0,
+        expArgs.length ? calls.length && passed === calls.length : calls.length === 0,
         "expected " + this._obj + " to have been always called with #{exp} but got " + passed + " out of " + calls.length,
         "expected " + this._obj + " to have been always called with #{exp} but got " + passed + " out of " + calls.length,
         "expected " + this._obj + " to have not always been called with #{exp}",
         "expected " + this._obj + " to have not always been called with #{exp}",
         expArgs
         expArgs
       );
       );
     } else if (nthCall) {
     } else if (nthCall) {
       const ordinalNumber = generateOrdinalNumber(nthCall), actArgs = calls[nthCall - 1];
       const ordinalNumber = generateOrdinalNumber(nthCall), actArgs = calls[nthCall - 1];
-      new Assertion(this._obj).to.be.have.been.called.min(nthCall);
+      new Assertion(this._obj).to.have.been.called.min(nthCall);
       this.assert(
       this.assert(
         nthCallWith(spy, nthCall - 1, expArgs),
         nthCallWith(spy, nthCall - 1, expArgs),
         "expected " + this._obj + " to have been called at the " + ordinalNumber + " time with #{exp} but got #{act}",
         "expected " + this._obj + " to have been called at the " + ordinalNumber + " time with #{exp} but got #{act}",
@@ -179,9 +179,8 @@ function chaiSpies(chai, _) {
       _.flag(this, "spy always", true);
       _.flag(this, "spy always", true);
     }
     }
   });
   });
-  Assertion.addMethod("exactly", function() {
+  Assertion.addMethod("exactly", function(...args) {
     new Assertion(this._obj).to.be.spy;
     new Assertion(this._obj).to.be.spy;
-    const args = [].slice.call(arguments, 0);
     this.assert(
     this.assert(
       this._obj.calls.length === args[0],
       this._obj.calls.length === args[0],
       "expected " + this._obj + " to have been called #{exp} times but got #{act}",
       "expected " + this._obj + " to have been called #{exp} times but got #{act}",

+ 5 - 8
src/chai/chai-spies.js

@@ -126,10 +126,9 @@ export function chaiSpies(chai, _) {
     return n + 'th';
     return n + 'th';
   }
   }
 
 
-  function assertWith() {
+  function assertWith(...expArgs) {
     new Assertion(this._obj).to.be.spy;
     new Assertion(this._obj).to.be.spy;
-    const expArgs = [].slice.call(arguments, 0)
-      , spy = this._obj
+    const spy = this._obj
       , calls = spy.calls
       , calls = spy.calls
       , always = _.flag(this, 'spy always')
       , always = _.flag(this, 'spy always')
       , nthCall = _.flag(this, 'spy nth call with');
       , nthCall = _.flag(this, 'spy nth call with');
@@ -137,7 +136,7 @@ export function chaiSpies(chai, _) {
     if (always) {
     if (always) {
       const passed = numberOfCallsWith(spy, expArgs);
       const passed = numberOfCallsWith(spy, expArgs);
       this.assert(
       this.assert(
-          arguments.length
+          expArgs.length
             ? calls.length && passed === calls.length
             ? calls.length && passed === calls.length
             : calls.length === 0
             : calls.length === 0
         , 'expected ' + this._obj + ' to have been always called with #{exp} but got ' + passed + ' out of ' + calls.length
         , 'expected ' + this._obj + ' to have been always called with #{exp} but got ' + passed + ' out of ' + calls.length
@@ -147,7 +146,7 @@ export function chaiSpies(chai, _) {
     } else if (nthCall) {
     } else if (nthCall) {
       const ordinalNumber = generateOrdinalNumber(nthCall),
       const ordinalNumber = generateOrdinalNumber(nthCall),
           actArgs = calls[nthCall - 1];
           actArgs = calls[nthCall - 1];
-      new Assertion(this._obj).to.be.have.been.called.min(nthCall);
+      new Assertion(this._obj).to.have.been.called.min(nthCall);
       this.assert(
       this.assert(
           nthCallWith(spy, nthCall - 1, expArgs)
           nthCallWith(spy, nthCall - 1, expArgs)
         , 'expected ' + this._obj + ' to have been called at the ' + ordinalNumber + ' time with #{exp} but got #{act}'
         , 'expected ' + this._obj + ' to have been called at the ' + ordinalNumber + ' time with #{exp} but got #{act}'
@@ -180,9 +179,8 @@ export function chaiSpies(chai, _) {
     }
     }
   });
   });
 
 
-  Assertion.addMethod('exactly', function () {
+  Assertion.addMethod('exactly', function (...args) {
     new Assertion(this._obj).to.be.spy;
     new Assertion(this._obj).to.be.spy;
-    const args = [].slice.call(arguments, 0);
     this.assert(
     this.assert(
         this._obj.calls.length === args[0]
         this._obj.calls.length === args[0]
       , 'expected ' + this._obj + ' to have been called #{exp} times but got #{act}'
       , 'expected ' + this._obj + ' to have been called #{exp} times but got #{act}'
@@ -196,7 +194,6 @@ export function chaiSpies(chai, _) {
     return function (n) {
     return function (n) {
       if (this._obj.__isSpy) {
       if (this._obj.__isSpy) {
         new Assertion(this._obj).to.be.spy;
         new Assertion(this._obj).to.be.spy;
-
         this.assert(
         this.assert(
             this._obj.calls.length > n
             this._obj.calls.length > n
           , 'expected ' + this._obj + ' to have been called more than #{exp} times but got #{act}'
           , 'expected ' + this._obj + ' to have been called more than #{exp} times but got #{act}'

+ 37 - 71
src/create-sandbox.spec.js

@@ -15,14 +15,9 @@ describe('Sandbox', function () {
   });
   });
 
 
   describe('Sandbox instance', function () {
   describe('Sandbox instance', function () {
-    let sandbox;
-
-    beforeEach(function () {
-      sandbox = createSandbox();
-    });
-
     describe('.on(target, methodNameOrImpl, customImplForMethod)', function () {
     describe('.on(target, methodNameOrImpl, customImplForMethod)', function () {
       it('should create a spy for a standalone function', function () {
       it('should create a spy for a standalone function', function () {
+        const sandbox = createSandbox();
         const targetFn = () => {};
         const targetFn = () => {};
         const fnSpy = sandbox.on(targetFn);
         const fnSpy = sandbox.on(targetFn);
         expect(fnSpy).to.be.a('function');
         expect(fnSpy).to.be.a('function');
@@ -31,6 +26,7 @@ describe('Sandbox', function () {
       });
       });
 
 
       it('should create a spy for a standalone function with a custom implementation', function () {
       it('should create a spy for a standalone function with a custom implementation', function () {
+        const sandbox = createSandbox();
         const targetFn = () => {};
         const targetFn = () => {};
         const customImpl = () => 'custom result';
         const customImpl = () => 'custom result';
         const fnSpy = sandbox.on(targetFn, customImpl);
         const fnSpy = sandbox.on(targetFn, customImpl);
@@ -39,6 +35,7 @@ describe('Sandbox', function () {
       });
       });
 
 
       it('should create a spy for an object method and replace the original method', function () {
       it('should create a spy for an object method and replace the original method', function () {
+        const sandbox = createSandbox();
         const obj = {method: () => 'original method'};
         const obj = {method: () => 'original method'};
         const methodSpy = sandbox.on(obj, 'method');
         const methodSpy = sandbox.on(obj, 'method');
         expect(obj.method).to.equal(methodSpy);
         expect(obj.method).to.equal(methodSpy);
@@ -46,6 +43,7 @@ describe('Sandbox', function () {
       });
       });
 
 
       it('should create a spy for an object method with a custom implementation', function () {
       it('should create a spy for an object method with a custom implementation', function () {
+        const sandbox = createSandbox();
         const obj = {method: () => 'original method'};
         const obj = {method: () => 'original method'};
         const customImpl = () => 'custom method';
         const customImpl = () => 'custom method';
         sandbox.on(obj, 'method', customImpl);
         sandbox.on(obj, 'method', customImpl);
@@ -53,6 +51,7 @@ describe('Sandbox', function () {
       });
       });
 
 
       it('should add the created spy to the internal spies array', function () {
       it('should add the created spy to the internal spies array', function () {
+        const sandbox = createSandbox();
         const targetFn1 = () => {};
         const targetFn1 = () => {};
         const targetFn2 = () => {};
         const targetFn2 = () => {};
         const spy1 = sandbox.on(targetFn1);
         const spy1 = sandbox.on(targetFn1);
@@ -64,6 +63,7 @@ describe('Sandbox', function () {
       });
       });
 
 
       it('should return the created spy instance', function () {
       it('should return the created spy instance', function () {
+        const sandbox = createSandbox();
         const targetFn = () => {};
         const targetFn = () => {};
         const returnedSpy = sandbox.on(targetFn);
         const returnedSpy = sandbox.on(targetFn);
         expect(returnedSpy).to.be.a('function');
         expect(returnedSpy).to.be.a('function');
@@ -72,90 +72,56 @@ describe('Sandbox', function () {
     });
     });
 
 
     describe('.restore()', function () {
     describe('.restore()', function () {
-      let obj1, originalMethod1;
-      let obj2, originalMethod2;
-      let standaloneFn1, standaloneFn2;
-      let spyObj1, spyObj2, spyFn1, spyFn2;
-
-      beforeEach(function () {
-        originalMethod1 = function () {
-          return 'original1';
-        };
-        obj1 = {method: originalMethod1};
-
-        originalMethod2 = function () {
-          return 'original2';
-        };
-        obj2 = {method: originalMethod2};
-
-        standaloneFn1 = function () {
-          return 'standalone1';
-        };
-        standaloneFn2 = function () {
-          return 'standalone2';
-        };
-
-        spyObj1 = sandbox.on(obj1, 'method');
-        spyFn1 = sandbox.on(standaloneFn1);
-        spyObj2 = sandbox.on(obj2, 'method');
-        spyFn2 = sandbox.on(standaloneFn2);
-
-        // вызов всех шпионов для наполнения истории
-        obj1.method(); // spyObj1
-        spyFn1();
-        obj2.method(); // spyObj2
-        spyFn2();
-
-        expect(spyObj1.callCount).to.equal(1);
-        expect(spyFn1.callCount).to.equal(1);
-        expect(spyObj2.callCount).to.equal(1);
-        expect(spyFn2.callCount).to.equal(1);
+      it('should restore original methods on objects', function () {
+        const sandbox = createSandbox();
+        const originalMethod = () => 'original';
+        const obj = {method: originalMethod};
+        sandbox.on(obj, 'method');
+        expect(obj.method).to.not.equal(originalMethod);
+        sandbox.restore();
+        expect(obj.method).to.equal(originalMethod);
+        expect(obj.method()).to.equal('original');
       });
       });
 
 
-      it('should call restore() on all spies in the sandbox', function () {
+      it('should reset call history for all spies', function () {
+        const sandbox = createSandbox();
+        const fn = () => {};
+        const spy = sandbox.on(fn);
+        spy();
+        expect(spy.called).to.be.true;
+        expect(spy.callCount).to.equal(1);
         sandbox.restore();
         sandbox.restore();
-        // проверка восстановления методов объектов
-        expect(obj1.method).to.equal(originalMethod1);
-        expect(obj1.method()).to.equal('original1');
-        expect(obj2.method).to.equal(originalMethod2);
-        expect(obj2.method()).to.equal('original2');
-        // проверка сброса истории
-        expect(spyObj1.callCount).to.equal(0);
-        expect(spyObj1.called).to.be.false;
-        expect(spyFn1.callCount).to.equal(0);
-        expect(spyFn1.called).to.be.false;
-        expect(spyObj2.callCount).to.equal(0);
-        expect(spyObj2.called).to.be.false;
-        expect(spyFn2.callCount).to.equal(0);
-        expect(spyFn2.called).to.be.false;
+        expect(spy.called).to.be.false;
+        expect(spy.callCount).to.equal(0);
       });
       });
 
 
       it('should clear the internal spies array', function () {
       it('should clear the internal spies array', function () {
-        expect(sandbox.spies).to.have.lengthOf(4);
+        const sandbox = createSandbox();
+        sandbox.on(() => {});
+        sandbox.on({m: () => {}}, 'm');
+        expect(sandbox.spies).to.have.lengthOf(2);
         sandbox.restore();
         sandbox.restore();
         expect(sandbox.spies).to.be.an('array').that.is.empty;
         expect(sandbox.spies).to.be.an('array').that.is.empty;
       });
       });
 
 
-      it('should return the Sandbox instance for chaining (if other methods were added)', function () {
+      it('should return the Sandbox instance for chaining', function () {
+        const sandbox = createSandbox();
         const returnedValue = sandbox.restore();
         const returnedValue = sandbox.restore();
         expect(returnedValue).to.equal(sandbox);
         expect(returnedValue).to.equal(sandbox);
       });
       });
 
 
-      it('should be idempotent - calling restore multiple times should not error', function () {
-        // первый вызов restore
+      it('should be idempotent (calling restore multiple times does not throw)', function () {
+        const sandbox = createSandbox();
+        const obj = {method: () => {}};
+        sandbox.on(obj, 'method');
         sandbox.restore();
         sandbox.restore();
-        // второй вызов restore
         expect(() => sandbox.restore()).to.not.throw();
         expect(() => sandbox.restore()).to.not.throw();
-        // проверки состояний после второго вызова (должно быть таким же)
-        expect(obj1.method).to.equal(originalMethod1);
-        expect(spyObj1.callCount).to.equal(0);
-        expect(sandbox.spies).to.be.an('array').that.is.empty;
       });
       });
 
 
       it('should handle an empty spies array gracefully', function () {
       it('should handle an empty spies array gracefully', function () {
-        const emptySandbox = createSandbox();
-        expect(() => emptySandbox.restore()).to.not.throw();
-        expect(emptySandbox.spies).to.be.an('array').that.is.empty;
+        const sandbox = createSandbox();
+        expect(() => sandbox.restore()).to.not.throw();
+        expect(sandbox.spies).to.be.an('array').that.is.empty;
       });
       });
     });
     });
   });
   });

+ 24 - 141
src/create-spy.spec.js

@@ -13,8 +13,6 @@ describe('createSpy', function () {
     });
     });
 
 
     it('should throw when trying to spy on null', function () {
     it('should throw when trying to spy on null', function () {
-      // проверка генерации ошибки при попытке
-      // шпионить за значением null
       expect(() => createSpy(null)).to.throw(
       expect(() => createSpy(null)).to.throw(
         TypeError,
         TypeError,
         'Attempted to spy on null.',
         'Attempted to spy on null.',
@@ -22,15 +20,11 @@ describe('createSpy', function () {
     });
     });
 
 
     it('should throw if target is not a function and no method name is given', function () {
     it('should throw if target is not a function and no method name is given', function () {
-      // проверка генерации ошибки для не-функции
-      // без указания имени метода
-      // @ts-ignore
       expect(() => createSpy({})).to.throw(
       expect(() => createSpy({})).to.throw(
         TypeError,
         TypeError,
         'Attempted to spy on a non-function value. To spy on an object method, ' +
         'Attempted to spy on a non-function value. To spy on an object method, ' +
           'you must provide the method name as the second argument.',
           'you must provide the method name as the second argument.',
       );
       );
-      // @ts-ignore
       expect(() => createSpy(123)).to.throw(
       expect(() => createSpy(123)).to.throw(
         TypeError,
         TypeError,
         'Attempted to spy on a non-function value. To spy on an object method, ' +
         'Attempted to spy on a non-function value. To spy on an object method, ' +
@@ -39,10 +33,7 @@ describe('createSpy', function () {
     });
     });
 
 
     it('should throw if custom implementation for a function spy is not a function', function () {
     it('should throw if custom implementation for a function spy is not a function', function () {
-      // проверка генерации ошибки, если кастомная
-      // реализация для шпиона функции не является функцией
       const targetFn = () => {};
       const targetFn = () => {};
-      // @ts-ignore
       expect(() => createSpy(targetFn, 'not a function')).to.throw(
       expect(() => createSpy(targetFn, 'not a function')).to.throw(
         TypeError,
         TypeError,
         'When spying on a function, the second argument (custom implementation) must be a function if provided.',
         'When spying on a function, the second argument (custom implementation) must be a function if provided.',
@@ -50,10 +41,7 @@ describe('createSpy', function () {
     });
     });
 
 
     it('should throw if trying to spy on a non-existent method', function () {
     it('should throw if trying to spy on a non-existent method', function () {
-      // проверка генерации ошибки при попытке
-      // шпионить за несуществующим методом объекта
       const obj = {};
       const obj = {};
-      // @ts-ignore
       expect(() => createSpy(obj, 'nonExistentMethod')).to.throw(
       expect(() => createSpy(obj, 'nonExistentMethod')).to.throw(
         TypeError,
         TypeError,
         'Attempted to spy on a non-existent property: "nonExistentMethod"',
         'Attempted to spy on a non-existent property: "nonExistentMethod"',
@@ -61,10 +49,7 @@ describe('createSpy', function () {
     });
     });
 
 
     it('should throw if trying to spy on a non-function property of an object', function () {
     it('should throw if trying to spy on a non-function property of an object', function () {
-      // проверка генерации ошибки при попытке
-      // шпионить за свойством объекта, не являющимся функцией
       const obj = {prop: 123};
       const obj = {prop: 123};
-      // @ts-ignore
       expect(() => createSpy(obj, 'prop')).to.throw(
       expect(() => createSpy(obj, 'prop')).to.throw(
         TypeError,
         TypeError,
         'Attempted to spy on "prop" which is not a function. It is a "number".',
         'Attempted to spy on "prop" which is not a function. It is a "number".',
@@ -72,10 +57,7 @@ describe('createSpy', function () {
     });
     });
 
 
     it('should throw if custom implementation for a method spy is not a function', function () {
     it('should throw if custom implementation for a method spy is not a function', function () {
-      // проверка генерации ошибки, если кастомная реализация
-      // для шпиона метода не является функцией
       const obj = {method: () => {}};
       const obj = {method: () => {}};
-      // @ts-ignore
       expect(() => createSpy(obj, 'method', 'not a function')).to.throw(
       expect(() => createSpy(obj, 'method', 'not a function')).to.throw(
         TypeError,
         TypeError,
         'When spying on a method, the third argument (custom implementation) must be a function if provided.',
         'When spying on a method, the third argument (custom implementation) must be a function if provided.',
@@ -85,110 +67,65 @@ describe('createSpy', function () {
 
 
   describe('when spying on a standalone function', function () {
   describe('when spying on a standalone function', function () {
     it('should return a function that is the spy', function () {
     it('should return a function that is the spy', function () {
-      // создание шпиона для пустой функции
       const targetFn = () => {};
       const targetFn = () => {};
       const spy = createSpy(targetFn);
       const spy = createSpy(targetFn);
-      // проверка того, что шпион
-      // является функцией
       expect(spy).to.be.a('function');
       expect(spy).to.be.a('function');
     });
     });
 
 
     it('should not be called initially', function () {
     it('should not be called initially', function () {
-      // создание шпиона
       const spy = createSpy(function () {});
       const spy = createSpy(function () {});
-      // первоначальное состояние свойства called
       expect(spy.called).to.be.false;
       expect(spy.called).to.be.false;
-      // первоначальное значение счетчика вызовов
       expect(spy.callCount).to.be.eq(0);
       expect(spy.callCount).to.be.eq(0);
     });
     });
 
 
     it('should track calls and arguments', function () {
     it('should track calls and arguments', function () {
-      // создание шпиона для функции,
-      // возвращающей сумму аргументов
       const sum = (a, b) => a + b;
       const sum = (a, b) => a + b;
       const spy = createSpy(sum);
       const spy = createSpy(sum);
-      // первый вызов шпиона
       spy(1, 2);
       spy(1, 2);
-      // второй вызов шпиона
       spy(3, 4);
       spy(3, 4);
-
-      // состояние свойства called
-      // после вызовов
       expect(spy.called).to.be.true;
       expect(spy.called).to.be.true;
-      // значение счетчика вызовов
       expect(spy.callCount).to.be.eq(2);
       expect(spy.callCount).to.be.eq(2);
-
-      // проверка аргументов первого вызова
       expect(spy.calls[0].args).to.deep.equal([1, 2]);
       expect(spy.calls[0].args).to.deep.equal([1, 2]);
-      // проверка аргументов второго вызова
       expect(spy.calls[1].args).to.deep.equal([3, 4]);
       expect(spy.calls[1].args).to.deep.equal([3, 4]);
     });
     });
 
 
     it('should call the original function and return its value by default', function () {
     it('should call the original function and return its value by default', function () {
-      // создание функции, возвращающей
-      // определенное значение
       const originalFn = () => 'original value';
       const originalFn = () => 'original value';
       const spy = createSpy(originalFn);
       const spy = createSpy(originalFn);
-      // вызов шпиона и сохранение результата
       const result = spy();
       const result = spy();
-
-      // проверка возвращенного значения
       expect(result).to.be.eq('original value');
       expect(result).to.be.eq('original value');
-      // проверка того, что шпион был вызван
       expect(spy.called).to.be.true;
       expect(spy.called).to.be.true;
     });
     });
 
 
     it('should use the custom implementation if provided', function () {
     it('should use the custom implementation if provided', function () {
-      // создание оригинальной функции и
-      // пользовательской реализации
       const originalFn = () => 'original';
       const originalFn = () => 'original';
       const customImpl = () => 'custom';
       const customImpl = () => 'custom';
       const spy = createSpy(originalFn, customImpl);
       const spy = createSpy(originalFn, customImpl);
-      // вызов шпиона и сохранение результата
       const result = spy();
       const result = spy();
-
-      // проверка того, что возвращено значение
-      // из пользовательской реализации
       expect(result).to.be.eq('custom');
       expect(result).to.be.eq('custom');
-      // проверка свойства called
       expect(spy.called).to.be.true;
       expect(spy.called).to.be.true;
     });
     });
 
 
     it('should preserve `this` context for the original function', function () {
     it('should preserve `this` context for the original function', function () {
-      // определение объекта с методом, который
-      // будет использоваться как target функция
       const contextObj = {val: 10};
       const contextObj = {val: 10};
       function originalFn() {
       function originalFn() {
         return this.val;
         return this.val;
       }
       }
       const spy = createSpy(originalFn);
       const spy = createSpy(originalFn);
-      // вызов шпиона с привязкой контекста
       const result = spy.call(contextObj);
       const result = spy.call(contextObj);
-
-      // проверка возвращенного значения, которое
-      // зависит от контекста this
       expect(result).to.be.eq(10);
       expect(result).to.be.eq(10);
-      // проверка сохраненного контекста
-      // в информации о вызове
       expect(spy.calls[0].thisArg).to.be.eq(contextObj);
       expect(spy.calls[0].thisArg).to.be.eq(contextObj);
     });
     });
 
 
     it('should preserve `this` context for the custom implementation', function () {
     it('should preserve `this` context for the custom implementation', function () {
-      // определение объекта и пользовательской реализации,
-      // использующей контекст this
       const contextObj = {val: 20};
       const contextObj = {val: 20};
       const originalFn = () => {};
       const originalFn = () => {};
       function customImpl() {
       function customImpl() {
         return this.val;
         return this.val;
       }
       }
       const spy = createSpy(originalFn, customImpl);
       const spy = createSpy(originalFn, customImpl);
-      // вызов шпиона с привязкой контекста
       const result = spy.call(contextObj);
       const result = spy.call(contextObj);
-
-      // проверка возвращенного значения из
-      // пользовательской реализации
       expect(result).to.be.eq(20);
       expect(result).to.be.eq(20);
-      // проверка сохраненного контекста
       expect(spy.calls[0].thisArg).to.be.eq(contextObj);
       expect(spy.calls[0].thisArg).to.be.eq(contextObj);
     });
     });
 
 
@@ -196,15 +133,10 @@ describe('createSpy', function () {
       it('should reset its history and not throw', function () {
       it('should reset its history and not throw', function () {
         const standaloneFn = () => 'standalone result';
         const standaloneFn = () => 'standalone result';
         const fnSpy = createSpy(standaloneFn);
         const fnSpy = createSpy(standaloneFn);
-        // вызов шпиона, чтобы у него была история
-        // @ts-ignore
         fnSpy('call standalone');
         fnSpy('call standalone');
         expect(fnSpy.called).to.be.true;
         expect(fnSpy.called).to.be.true;
         expect(fnSpy.callCount).to.be.eq(1);
         expect(fnSpy.callCount).to.be.eq(1);
-        expect(fnSpy.calls[0].args).to.deep.equal(['call standalone']);
-        // проверка, что вызов restore не вызывает ошибок
         expect(() => fnSpy.restore()).to.not.throw();
         expect(() => fnSpy.restore()).to.not.throw();
-        // проверки сброса истории
         expect(fnSpy.callCount).to.be.eq(0);
         expect(fnSpy.callCount).to.be.eq(0);
         expect(fnSpy.called).to.be.false;
         expect(fnSpy.called).to.be.false;
       });
       });
@@ -212,90 +144,61 @@ describe('createSpy', function () {
   });
   });
 
 
   describe('when spying on an object method', function () {
   describe('when spying on an object method', function () {
-    // определение объекта и его метода
-    // для каждого теста в этом блоке
-    let obj;
-    let originalMethodImpl; // для проверки восстановления
-
-    beforeEach(function () {
-      // это функция, которая будет телом
-      // beforeEach, поэтому комментарии здесь уместны
-      // инициализация объекта с методом
-      // перед каждым тестом
-      originalMethodImpl = function (val) {
-        return `original: ${this.name} ${val}`;
-      };
-      obj = {
-        name: 'TestObj',
-        method: originalMethodImpl,
-      };
-    });
-
     it('should replace the original method with the spy', function () {
     it('should replace the original method with the spy', function () {
-      // создание шпиона для метода объекта
+      const obj = {method: () => {}};
       const spy = createSpy(obj, 'method');
       const spy = createSpy(obj, 'method');
-      // проверка того, что свойство объекта
-      // теперь является шпионом
       expect(obj.method).to.be.eq(spy);
       expect(obj.method).to.be.eq(spy);
-      // проверка того, что шпион является функцией
       expect(obj.method).to.be.a('function');
       expect(obj.method).to.be.a('function');
     });
     });
 
 
     it('should call the original method with object context and return its value', function () {
     it('should call the original method with object context and return its value', function () {
-      // создание шпиона для метода
+      const originalMethodImpl = function (val) {
+        return `original: ${this.name} ${val}`;
+      };
+      const obj = {
+        name: 'TestObj',
+        method: originalMethodImpl,
+      };
       const spy = createSpy(obj, 'method');
       const spy = createSpy(obj, 'method');
-      // вызов подмененного метода
       const result = obj.method('arg1');
       const result = obj.method('arg1');
-
-      // проверка возвращенного значения
-      // от оригинального метода
       expect(result).to.be.eq('original: TestObj arg1');
       expect(result).to.be.eq('original: TestObj arg1');
-      // проверка счетчика вызовов
       expect(spy.callCount).to.be.eq(1);
       expect(spy.callCount).to.be.eq(1);
-      // проверка сохраненного контекста
       expect(spy.calls[0].thisArg).to.be.eq(obj);
       expect(spy.calls[0].thisArg).to.be.eq(obj);
-      // проверка сохраненных аргументов
       expect(spy.calls[0].args).to.deep.equal(['arg1']);
       expect(spy.calls[0].args).to.deep.equal(['arg1']);
     });
     });
 
 
     it('should use custom implementation with object context if provided', function () {
     it('should use custom implementation with object context if provided', function () {
-      // определение пользовательской реализации
+      const obj = {
+        name: 'TestObj',
+        method: () => {},
+      };
       const customImpl = function (val) {
       const customImpl = function (val) {
         return `custom: ${this.name} ${val}`;
         return `custom: ${this.name} ${val}`;
       };
       };
-      // создание шпиона с пользовательской реализацией
       const spy = createSpy(obj, 'method', customImpl);
       const spy = createSpy(obj, 'method', customImpl);
-      // вызов подмененного метода
       const result = obj.method('argCustom');
       const result = obj.method('argCustom');
-
-      // проверка возвращенного значения
-      // от пользовательской реализации
       expect(result).to.be.eq('custom: TestObj argCustom');
       expect(result).to.be.eq('custom: TestObj argCustom');
-      // проверка счетчика вызовов
       expect(spy.callCount).to.be.eq(1);
       expect(spy.callCount).to.be.eq(1);
-      // проверка сохраненного контекста
       expect(spy.calls[0].thisArg).to.be.eq(obj);
       expect(spy.calls[0].thisArg).to.be.eq(obj);
     });
     });
 
 
     describe('.restore()', function () {
     describe('.restore()', function () {
       it('should put the original method back and reset spy history', function () {
       it('should put the original method back and reset spy history', function () {
-        // создание шпиона для метода
+        const originalMethodImpl = function (val) {
+          return `original: ${this.name} ${val}`;
+        };
+        const obj = {
+          name: 'TestObj',
+          method: originalMethodImpl,
+        };
         const spy = createSpy(obj, 'method');
         const spy = createSpy(obj, 'method');
-        // вызов шпиона, чтобы у него была история
         obj.method('call before restore');
         obj.method('call before restore');
         expect(spy.called).to.be.true;
         expect(spy.called).to.be.true;
-        expect(spy.callCount).to.be.eq(1);
         expect(obj.method).to.be.eq(spy);
         expect(obj.method).to.be.eq(spy);
-        // вызов метода restore на шпионе
         spy.restore();
         spy.restore();
-        // проверка, что оригинальный метод восстановлен
         expect(obj.method).to.be.eq(originalMethodImpl);
         expect(obj.method).to.be.eq(originalMethodImpl);
-        // вызов восстановленного метода
-        // для проверки его работоспособности
         const result = obj.method('call after restore');
         const result = obj.method('call after restore');
-        // проверка результата вызова оригинального метода
         expect(result).to.be.eq('original: TestObj call after restore');
         expect(result).to.be.eq('original: TestObj call after restore');
-        // проверки сброса истории
         expect(spy.callCount).to.be.eq(0);
         expect(spy.callCount).to.be.eq(0);
         expect(spy.called).to.be.false;
         expect(spy.called).to.be.false;
       });
       });
@@ -306,7 +209,6 @@ describe('createSpy', function () {
             return 'own';
             return 'own';
           },
           },
         };
         };
-        expect(Object.prototype.hasOwnProperty.call(obj, 'fn')).to.be.true;
         const spy = createSpy(obj, 'fn');
         const spy = createSpy(obj, 'fn');
         expect(obj.fn).to.be.eq(spy);
         expect(obj.fn).to.be.eq(spy);
         spy.restore();
         spy.restore();
@@ -323,7 +225,6 @@ describe('createSpy', function () {
         const instance = new Base();
         const instance = new Base();
         expect(Object.prototype.hasOwnProperty.call(instance, 'method')).to.be
         expect(Object.prototype.hasOwnProperty.call(instance, 'method')).to.be
           .false;
           .false;
-        expect(instance.method()).to.be.eq('prototype');
         const spy = createSpy(instance, 'method');
         const spy = createSpy(instance, 'method');
         expect(Object.prototype.hasOwnProperty.call(instance, 'method')).to.be
         expect(Object.prototype.hasOwnProperty.call(instance, 'method')).to.be
           .true;
           .true;
@@ -337,29 +238,15 @@ describe('createSpy', function () {
   });
   });
 
 
   describe('spy properties and methods', function () {
   describe('spy properties and methods', function () {
-    // объявление шпиона для использования в тестах
-    let spy;
-    // определение функции, которая
-    // будет объектом шпионажа
-    const targetFn = (a, b) => {
-      if (a === 0) throw new Error('zero error');
-      return a + b;
-    };
-
-    beforeEach(function () {
-      // это функция, которая будет телом
-      // beforeEach, поэтому комментарии здесь уместны
-      // создание нового шпиона перед
-      // каждым тестом в этом блоке
-      spy = createSpy(targetFn);
-    });
-
     it('should have the __isSpy property with true value', function () {
     it('should have the __isSpy property with true value', function () {
+      const spy = createSpy(() => {});
       expect(spy['__isSpy']).to.be.true;
       expect(spy['__isSpy']).to.be.true;
     });
     });
 
 
     describe('.calls', function () {
     describe('.calls', function () {
       it('should return an array of CallInfo', function () {
       it('should return an array of CallInfo', function () {
+        const targetFn = (a, b) => a + b;
+        const spy = createSpy(targetFn);
         expect(spy.calls).to.be.eql([]);
         expect(spy.calls).to.be.eql([]);
         spy(1, 2);
         spy(1, 2);
         expect(spy.calls[0]).to.be.eql({
         expect(spy.calls[0]).to.be.eql({
@@ -381,21 +268,17 @@ describe('createSpy', function () {
 
 
     describe('.callCount and .called', function () {
     describe('.callCount and .called', function () {
       it('should have callCount = 0 and called = false initially', function () {
       it('should have callCount = 0 and called = false initially', function () {
-        // начальное состояние счетчика вызовов
+        const spy = createSpy(() => {});
         expect(spy.callCount).to.be.eq(0);
         expect(spy.callCount).to.be.eq(0);
-        // начальное состояние флага called
         expect(spy.called).to.be.false;
         expect(spy.called).to.be.false;
       });
       });
 
 
       it('should update after calls', function () {
       it('should update after calls', function () {
-        // первый вызов шпиона
+        const spy = createSpy(() => {});
         spy(1, 1);
         spy(1, 1);
-        // состояние после первого вызова
         expect(spy.callCount).to.be.eq(1);
         expect(spy.callCount).to.be.eq(1);
         expect(spy.called).to.be.true;
         expect(spy.called).to.be.true;
-        // второй вызов шпиона
         spy(2, 2);
         spy(2, 2);
-        // состояние после второго вызова
         expect(spy.callCount).to.be.eq(2);
         expect(spy.callCount).to.be.eq(2);
       });
       });
     });
     });