Browse Source

refactor: renames group.on to group.spy

e22m4u 2 days ago
parent
commit
6fcd91aecb

+ 12 - 12
README.md

@@ -21,7 +21,7 @@
     - [spy.restore()](#spyrestore)
   - [Функция `createSpiesGroup`](#функция-createspiesgroup)
   - [Методы группы шпионов](#методы-группы-шпионов)
-    - [group.on(...)](#groupon)
+    - [group.spy(...)](#groupon)
     - [group.restore()](#grouprestore)
 - [Тесты](#тесты)
 - [Лицензия](#лицензия)
@@ -187,12 +187,12 @@ function standaloneLogger(message) {
 const group = createSpiesGroup();
 
 // добавление шпионов в группу:
-//   метод group.on() работает аналогично createSpy(),
+//   метод group.spy() работает аналогично createSpy(),
 //   но добавляет шпиона в группу и возвращает созданного
 //   шпиона
-const fetchDataSpy = group.on(service, 'fetchData');
-const processItemSpy = group.on(service, 'processItem');
-const loggerSpy = group.on(standaloneLogger);
+const fetchDataSpy = group.spy(service, 'fetchData');
+const processItemSpy = group.spy(service, 'processItem');
+const loggerSpy = group.spy(standaloneLogger);
 
 // так как методы заменяются шпионами прямо на объекте,
 // допустимо вызывать непосредственно их
@@ -341,7 +341,7 @@ expect(spy).on.nth(10).be.called.with('result');
 
 ### Свойства и методы шпиона
 
-Каждая функция-шпион, возвращаемая `createSpy` (или `group.on`), обладает
+Каждая функция-шпион, возвращаемая `createSpy` (или `group.spy`), обладает
 следующими свойствами и методами:
 
 #### spy(...args)
@@ -468,17 +468,17 @@ const group = createSpiesGroup();
 
 Экземпляр `SpiesGroup` имеет следующие методы:
 
-#### group.on(...)
+#### group.spy(...)
 
 Создает шпиона и добавляет его в группу.
 
 Сигнатуры вызова:
 
 1.  Отслеживание отдельной функции:  
-    `group.on(targetFn, [customImpl])`
+    `group.spy(targetFn, [customImpl])`
 
 2.  Отслеживание метода объекта:  
-    `group.on(targetObject, methodName, [customImpl])`
+    `group.spy(targetObject, methodName, [customImpl])`
 
 Возвращает:
 
@@ -490,7 +490,7 @@ const group = createSpiesGroup();
 const group = createSpiesGroup();
 const obj = {greet: () => 'Hello'};
 
-const greetSpy = group.on(obj, 'greet');
+const greetSpy = group.spy(obj, 'greet');
 // obj.greet теперь шпион, и greetSpy добавлен в группу
 obj.greet();
 console.log(greetSpy.called); // true
@@ -525,8 +525,8 @@ const service = {
 function utilFn() { /* ... */ }
 
 // создание шпионов
-const processSpy = group.on(service, 'process');
-const utilSpy = group.on(utilFn);
+const processSpy = group.spy(service, 'process');
+const utilSpy = group.spy(utilFn);
 
 // вызов отслеживаемого метода
 // и шпиона одиночной функции

+ 1 - 1
dist/cjs/index.cjs

@@ -431,7 +431,7 @@ var _SpiesGroup = class _SpiesGroup {
    * @param {Function} [customImplForMethod]
    * @returns {Function}
    */
-  on(target, methodNameOrImpl, customImplForMethod) {
+  spy(target, methodNameOrImpl, customImplForMethod) {
     const spy = createSpy(target, methodNameOrImpl, customImplForMethod);
     this.spies.push(spy);
     return spy;

+ 4 - 0
src/chai/chai-spies.d.ts

@@ -1,5 +1,9 @@
 declare global {
   namespace Chai {
+    /**
+     * Определение LanguageChains.on нужно, чтобы TypeScript разрешил
+     * писать предложения типа `expect(spy).on.nth(3)...`.
+     */
     interface LanguageChains {
       on: Assertion;
     }

+ 1 - 1
src/chai/chai-spies.spec.js

@@ -22,7 +22,7 @@ describe('chaiSpies', function () {
     expect(spy).to.have.been.called();
   });
 
-  it('should assert that something has been spied on on a certain index', function () {
+  it('should assert that something has been spied on a certain index', function () {
     const fn = () => undefined;
     const spy = createSpy(fn);
     spy('foobar1');

+ 2 - 2
src/create-spies-group.d.ts

@@ -20,7 +20,7 @@ export declare class SpiesGroup {
    * @param target
    * @param customImpl
    */
-  on<TFunc extends AnyCallable>(
+  spy<TFunc extends AnyCallable>(
     target: TFunc,
     customImpl?: TFunc,
   ): Spy<TFunc>;
@@ -34,7 +34,7 @@ export declare class SpiesGroup {
    * @param methodName
    * @param customImpl
    */
-  on<TObj extends object, K extends MethodKey<TObj>>(
+  spy<TObj extends object, K extends MethodKey<TObj>>(
     target: TObj,
     methodName: K,
     customImpl?: AnyCallable,

+ 1 - 1
src/create-spies-group.js

@@ -21,7 +21,7 @@ export class SpiesGroup {
    * @param {Function} [customImplForMethod]
    * @returns {Function}
    */
-  on(target, methodNameOrImpl, customImplForMethod) {
+  spy(target, methodNameOrImpl, customImplForMethod) {
     const spy = createSpy(target, methodNameOrImpl, customImplForMethod);
     this.spies.push(spy);
     return spy;

+ 12 - 12
src/create-spies-group.spec.js

@@ -21,29 +21,29 @@ describe('SpiesGroup', function () {
       group = createSpiesGroup();
     });
 
-    describe('.on(target, methodNameOrImpl, customImplForMethod)', function () {
+    describe('.spy(target, methodNameOrImpl, customImplForMethod)', function () {
       it('should create a spy using createSpy with the given arguments', function () {
         const targetFn = () => {};
         const customImpl = () => {};
         // шпион для standalone функции
-        const fnSpy = group.on(targetFn);
+        const fnSpy = group.spy(targetFn);
         expect(fnSpy).to.be.a('function');
         // проверка, что это действительно шпион
         expect(fnSpy.callCount).to.equal(0);
         // шпион для standalone функции с кастомной реализацией
-        const fnSpyWithImpl = group.on(targetFn, customImpl);
+        const fnSpyWithImpl = group.spy(targetFn, customImpl);
         // вызов для проверки кастомной реализации
         fnSpyWithImpl();
         expect(fnSpyWithImpl.calls[0].returnValue).to.equal(customImpl());
         // шпион для метода объекта
         const obj = {method: () => 'original method'};
-        const methodSpy = group.on(obj, 'method');
+        const methodSpy = group.spy(obj, 'method');
         // проверка замены метода
         expect(obj.method).to.equal(methodSpy);
         // шпион для метода объекта с кастомной реализацией
         const objWithCustom = {method: () => 'original method 2'};
         const customMethodImpl = () => 'custom method';
-        group.on(objWithCustom, 'method', customMethodImpl);
+        group.spy(objWithCustom, 'method', customMethodImpl);
         // проверка вызова кастомной реализации
         expect(objWithCustom.method()).to.equal('custom method');
       });
@@ -51,17 +51,17 @@ describe('SpiesGroup', function () {
       it('should add the created spy to the internal spies array', function () {
         const targetFn1 = () => {};
         const targetFn2 = () => {};
-        const spy1 = group.on(targetFn1);
+        const spy1 = group.spy(targetFn1);
         expect(group.spies).to.have.lengthOf(1);
         expect(group.spies[0]).to.equal(spy1);
-        const spy2 = group.on(targetFn2);
+        const spy2 = group.spy(targetFn2);
         expect(group.spies).to.have.lengthOf(2);
         expect(group.spies[1]).to.equal(spy2);
       });
 
       it('should return the created spy instance', function () {
         const targetFn = () => {};
-        const returnedSpy = group.on(targetFn);
+        const returnedSpy = group.spy(targetFn);
         expect(returnedSpy).to.be.a('function');
         // проверка, что это тот же шпион, что и в массиве
         expect(group.spies[0]).to.equal(returnedSpy);
@@ -92,10 +92,10 @@ describe('SpiesGroup', function () {
           return 'standalone2';
         };
 
-        spyObj1 = group.on(obj1, 'method');
-        spyFn1 = group.on(standaloneFn1);
-        spyObj2 = group.on(obj2, 'method');
-        spyFn2 = group.on(standaloneFn2);
+        spyObj1 = group.spy(obj1, 'method');
+        spyFn1 = group.spy(standaloneFn1);
+        spyObj2 = group.spy(obj2, 'method');
+        spyFn2 = group.spy(standaloneFn2);
 
         // вызов всех шпионов для наполнения истории
         obj1.method(); // spyObj1

+ 3 - 4
src/create-spy.d.ts

@@ -67,10 +67,9 @@ export interface Spy<TFunc extends AnyCallable = AnyCallable> {
   readonly called: boolean;
 
   /**
-   * Восстанавливает оригинальный метод,
-   * если шпион был создан для метода объекта,
-   * и сбрасывает историю вызовов, если шпион
-   * был создан для отдельной функции.
+   * Восстанавливает оригинальный метод
+   * (если шпион создан для метода объекта)
+   * и сбрасывает историю вызовов.
    */
   restore(): void;
 }