Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore: migrate jest-mock to TypeScript #7847

Merged
merged 9 commits into from
Feb 10, 2019
Merged

Conversation

thymikee
Copy link
Collaborator

@thymikee thymikee commented Feb 10, 2019

Summary

build/index.js

diff --git a/packages/jest-mock/build/index.js b/packages/jest-mock/build/index.js
index 76dc3630f..91ed19a0c 100644
--- a/packages/jest-mock/build/index.js
+++ b/packages/jest-mock/build/index.js
@@ -5,8 +5,6 @@
  *
  * This source code is licensed under the MIT license found in the
  * LICENSE file in the root directory of this source tree.
- *
- *
  */

 /**
@@ -83,63 +81,82 @@ function matchArity(fn, length) {

   switch (length) {
     case 1:
-      mockConstructor = function mockConstructor(a) {
+      mockConstructor = function mockConstructor(_a) {
         return fn.apply(this, arguments);
       };

       break;

     case 2:
-      mockConstructor = function mockConstructor(a, b) {
+      mockConstructor = function mockConstructor(_a, _b) {
         return fn.apply(this, arguments);
       };

       break;

     case 3:
-      mockConstructor = function mockConstructor(a, b, c) {
+      mockConstructor = function mockConstructor(_a, _b, _c) {
         return fn.apply(this, arguments);
       };

       break;

     case 4:
-      mockConstructor = function mockConstructor(a, b, c, d) {
+      mockConstructor = function mockConstructor(_a, _b, _c, _d) {
         return fn.apply(this, arguments);
       };

       break;

     case 5:
-      mockConstructor = function mockConstructor(a, b, c, d, e) {
+      mockConstructor = function mockConstructor(_a, _b, _c, _d, _e) {
         return fn.apply(this, arguments);
       };

       break;

     case 6:
-      mockConstructor = function mockConstructor(a, b, c, d, e, f) {
+      mockConstructor = function mockConstructor(_a, _b, _c, _d, _e, _f) {
         return fn.apply(this, arguments);
       };

       break;

     case 7:
-      mockConstructor = function mockConstructor(a, b, c, d, e, f, g) {
+      mockConstructor = function mockConstructor(_a, _b, _c, _d, _e, _f, _g) {
         return fn.apply(this, arguments);
       };

       break;

     case 8:
-      mockConstructor = function mockConstructor(a, b, c, d, e, f, g, h) {
+      mockConstructor = function mockConstructor(
+        _a,
+        _b,
+        _c,
+        _d,
+        _e,
+        _f,
+        _g,
+        _h
+      ) {
         return fn.apply(this, arguments);
       };

       break;

     case 9:
-      mockConstructor = function mockConstructor(a, b, c, d, e, f, g, h, i) {
+      mockConstructor = function mockConstructor(
+        _a,
+        _b,
+        _c,
+        _d,
+        _e,
+        _f,
+        _g,
+        _h,
+        _i
+      ) {
         return fn.apply(this, arguments);
       };

@@ -271,7 +288,7 @@ class ModuleMockerClass {
         const prop = ownNames[i];

         if (!isReadonlyProp(object, prop)) {
-          const propDesc = Object.getOwnPropertyDescriptor(object, prop);
+          const propDesc = Object.getOwnPropertyDescriptor(object, prop); // @ts-ignore Object.__esModule

           if ((propDesc !== undefined && !propDesc.get) || object.__esModule) {
             slots.add(prop);
@@ -344,10 +361,7 @@ class ModuleMockerClass {
     ) {
       return metadata.value;
     } else if (metadata.type === 'function') {
-      /* eslint-disable prefer-const */
       let f;
-      /* eslint-enable prefer-const */
-
       const prototype =
         (metadata.members &&
           metadata.members.prototype &&
@@ -357,13 +371,13 @@ class ModuleMockerClass {
       const prototypeSlots = this._getSlots(prototype);

       const mocker = this;
-      const mockConstructor = matchArity(function() {
+      const mockConstructor = matchArity(function(...args) {
         const mockState = mocker._ensureMockState(f);

         const mockConfig = mocker._ensureMockConfig(f);

         mockState.instances.push(this);
-        mockState.calls.push(Array.prototype.slice.call(arguments)); // Create and record an "incomplete" mock result immediately upon
+        mockState.calls.push(args); // Create and record an "incomplete" mock result immediately upon
         // calling rather than waiting for the mock to return. This avoids
         // issues caused by recursion where results can be recorded in the
         // wrong order.
@@ -396,8 +410,11 @@ class ModuleMockerClass {
                 // it easier to interact with mock instance call and
                 // return values
                 if (prototype[slot].type === 'function') {
-                  const protoImpl = this[slot];
-                  this[slot] = mocker.generateFromMetadata(prototype[slot]);
+                  // @ts-ignore no index signature
+                  const protoImpl = this[slot]; // @ts-ignore no index signature
+
+                  this[slot] = mocker.generateFromMetadata(prototype[slot]); // @ts-ignore no index signature
+
                   this[slot]._protoImpl = protoImpl;
                 }
               }); // Run the mock constructor implementation
@@ -471,7 +488,7 @@ class ModuleMockerClass {

       this._mockState.set(f, this._defaultMockState());

-      this._mockConfigRegistry.set(f, this._defaultMockConfig()); // $FlowFixMe - defineProperty getters not supported
+      this._mockConfigRegistry.set(f, this._defaultMockConfig());

       Object.defineProperty(f, 'mock', {
         configurable: false,
@@ -634,6 +651,9 @@ class ModuleMockerClass {
   }

   _generateMock(metadata, callbacks, refs) {
+    // metadata not compatible but it's the same type, maybe problem with
+    // overloading of _makeComponent and not _generateMock?
+    // @ts-ignore
     const mock = this._makeComponent(metadata);

     if (metadata.refID != null) {
@@ -644,7 +664,11 @@ class ModuleMockerClass {
       const slotMetadata = (metadata.members && metadata.members[slot]) || {};

       if (slotMetadata.ref != null) {
-        callbacks.push(() => (mock[slot] = refs[slotMetadata.ref]));
+        callbacks.push(
+          (function(ref) {
+            return () => (mock[slot] = refs[ref]);
+          })(slotMetadata.ref)
+        );
       } else {
         mock[slot] = this._generateMock(slotMetadata, callbacks, refs);
       }
@@ -709,9 +733,11 @@ class ModuleMockerClass {
       metadata.value = component;
       return metadata;
     } else if (type === 'function') {
-      metadata.name = component.name;
+      // @ts-ignore this is a function so it has a name
+      metadata.name = component.name; // @ts-ignore may be a mock

       if (component._isMockFunction === true) {
+        // @ts-ignore may be a mock
         metadata.mockImpl = component.getMockImplementation();
       }
     }
@@ -721,15 +747,14 @@ class ModuleMockerClass {
     let members = null; // Leave arrays alone

     if (type !== 'array') {
-      if (type !== 'undefined') {
       this._getSlots(component).forEach(slot => {
         if (
-            type === 'function' &&
+          type === 'function' && // @ts-ignore may be a mock
           component._isMockFunction === true &&
           slot.match(/^mock/)
         ) {
           return;
-          }
+        } // @ts-ignore no index signature

         const slotMetadata = this.getMetadata(component[slot], refs);

@@ -742,7 +767,6 @@ class ModuleMockerClass {
         }
       });
     }
-    }

     if (members) {
       metadata.members = members;
@@ -792,7 +816,7 @@ class ModuleMockerClass {
             this._typeOf(original) +
             ' given instead'
         );
-      }
+      } // @ts-ignore overriding original method with a Mock

       object[methodName] = this._makeComponent(
         {
@@ -801,7 +825,8 @@ class ModuleMockerClass {
         () => {
           object[methodName] = original;
         }
-      );
+      ); // @ts-ignore original method is now a Mock
+
       object[methodName].mockImplementation(function() {
         return original.apply(this, arguments);
       });
@@ -867,13 +894,12 @@ class ModuleMockerClass {
           type: 'function'
         },
         () => {
-          // $FlowFixMe
-          descriptor[accessType] = original; // $FlowFixMe
-
+          descriptor[accessType] = original;
           Object.defineProperty(obj, propertyName, descriptor);
         }
       );
       descriptor[accessType].mockImplementation(function() {
+        // @ts-ignore
         return original.apply(this, arguments);
       });
     }
@@ -900,6 +926,7 @@ class ModuleMockerClass {
   _typeOf(value) {
     return value == null ? '' + value : typeof value;
   }
-}
+} // TODO: bring this type export back once done with TS migration
+// export type ModuleMocker = ModuleMockerClass;

 module.exports = new ModuleMockerClass(global);

build-es5/index.js

diff --git a/packages/jest-mock/build-es5/index.js b/packages/jest-mock/build-es5/index.js
index eea6b7758..34d7668e1 100644
--- a/packages/jest-mock/build-es5/index.js
+++ b/packages/jest-mock/build-es5/index.js
@@ -91,7 +91,7 @@ return /******/ (function(modules) { // webpackBootstrap
 /******/
 /******/
 /******/ 	// Load entry module and return exports
-/******/ 	return __webpack_require__(__webpack_require__.s = "./packages/jest-mock/src/index.js");
+/******/ 	return __webpack_require__(__webpack_require__.s = "./packages/jest-mock/src/index.ts");
 /******/ })
 /************************************************************************/
 /******/ ({
@@ -129,9 +129,9 @@ module.exports = g;

 /***/ }),

-/***/ "./packages/jest-mock/src/index.js":
+/***/ "./packages/jest-mock/src/index.ts":
 /*!*****************************************!*\
-  !*** ./packages/jest-mock/src/index.js ***!
+  !*** ./packages/jest-mock/src/index.ts ***!
   \*****************************************/
 /*! no static exports found */
 /***/ (function(module, exports, __webpack_require__) {
@@ -152,8 +152,6 @@ function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _d
  *
  * This source code is licensed under the MIT license found in the
  * LICENSE file in the root directory of this source tree.
- *
- *
  */

 /**
@@ -178,63 +176,63 @@ function matchArity(fn, length) {

   switch (length) {
     case 1:
-      mockConstructor = function mockConstructor(a) {
+      mockConstructor = function mockConstructor(_a) {
         return fn.apply(this, arguments);
       };

       break;

     case 2:
-      mockConstructor = function mockConstructor(a, b) {
+      mockConstructor = function mockConstructor(_a, _b) {
         return fn.apply(this, arguments);
       };

       break;

     case 3:
-      mockConstructor = function mockConstructor(a, b, c) {
+      mockConstructor = function mockConstructor(_a, _b, _c) {
         return fn.apply(this, arguments);
       };

       break;

     case 4:
-      mockConstructor = function mockConstructor(a, b, c, d) {
+      mockConstructor = function mockConstructor(_a, _b, _c, _d) {
         return fn.apply(this, arguments);
       };

       break;

     case 5:
-      mockConstructor = function mockConstructor(a, b, c, d, e) {
+      mockConstructor = function mockConstructor(_a, _b, _c, _d, _e) {
         return fn.apply(this, arguments);
       };

       break;

     case 6:
-      mockConstructor = function mockConstructor(a, b, c, d, e, f) {
+      mockConstructor = function mockConstructor(_a, _b, _c, _d, _e, _f) {
         return fn.apply(this, arguments);
       };

       break;

     case 7:
-      mockConstructor = function mockConstructor(a, b, c, d, e, f, g) {
+      mockConstructor = function mockConstructor(_a, _b, _c, _d, _e, _f, _g) {
         return fn.apply(this, arguments);
       };

       break;

     case 8:
-      mockConstructor = function mockConstructor(a, b, c, d, e, f, g, h) {
+      mockConstructor = function mockConstructor(_a, _b, _c, _d, _e, _f, _g, _h) {
         return fn.apply(this, arguments);
       };

       break;

     case 9:
-      mockConstructor = function mockConstructor(a, b, c, d, e, f, g, h, i) {
+      mockConstructor = function mockConstructor(_a, _b, _c, _d, _e, _f, _g, _h, _i) {
         return fn.apply(this, arguments);
       };

@@ -336,7 +334,7 @@ function () {
           var prop = ownNames[i];

           if (!isReadonlyProp(object, prop)) {
-            var propDesc = Object.getOwnPropertyDescriptor(object, prop);
+            var propDesc = Object.getOwnPropertyDescriptor(object, prop); // @ts-ignore Object.__esModule

             if (propDesc !== undefined && !propDesc.get || object.__esModule) {
               slots.add(prop);
@@ -411,10 +409,7 @@ function () {
       } else if (metadata.type === 'constant' || metadata.type === 'collection' || metadata.type === 'null' || metadata.type === 'undefined') {
         return metadata.value;
       } else if (metadata.type === 'function') {
-        /* eslint-disable prefer-const */
         var f;
-        /* eslint-enable prefer-const */
-
         var prototype = metadata.members && metadata.members.prototype && metadata.members.prototype.members || {};

         var prototypeSlots = this._getSlots(prototype);
@@ -424,12 +419,16 @@ function () {
           var _this = this,
               _arguments = arguments;

+          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
+            args[_key] = arguments[_key];
+          }
+
           var mockState = mocker._ensureMockState(f);

           var mockConfig = mocker._ensureMockConfig(f);

           mockState.instances.push(this);
-          mockState.calls.push(Array.prototype.slice.call(arguments)); // Create and record an "incomplete" mock result immediately upon
+          mockState.calls.push(args); // Create and record an "incomplete" mock result immediately upon
           // calling rather than waiting for the mock to return. This avoids
           // issues caused by recursion where results can be recorded in the
           // wrong order.
@@ -462,14 +461,18 @@ function () {
                   // it easier to interact with mock instance call and
                   // return values
                   if (prototype[slot].type === 'function') {
-                    var protoImpl = _this[slot];
-                    _this[slot] = mocker.generateFromMetadata(prototype[slot]);
+                    // @ts-ignore
+                    var protoImpl = _this[slot]; // @ts-ignore
+
+                    _this[slot] = mocker.generateFromMetadata(prototype[slot]); // @ts-ignore
+
                     _this[slot]._protoImpl = protoImpl;
                   }
                 }); // Run the mock constructor implementation

-                var mockImpl = mockConfig.specificMockImpls.length ? mockConfig.specificMockImpls.shift() : mockConfig.mockImpl;
-                return mockImpl && mockImpl.apply(_this, _arguments);
+                var _mockImpl = mockConfig.specificMockImpls.length ? mockConfig.specificMockImpls.shift() : mockConfig.mockImpl;
+
+                return _mockImpl && _mockImpl.apply(_this, _arguments);
               }

               var returnValue = mockConfig.defaultReturnValue; // If return value is last set, either specific or default, i.e.
@@ -539,8 +542,7 @@ function () {

         this._mockState.set(f, this._defaultMockState());

-        this._mockConfigRegistry.set(f, this._defaultMockConfig()); // $FlowFixMe - defineProperty getters not supported
-
+        this._mockConfigRegistry.set(f, this._defaultMockConfig());

         Object.defineProperty(f, 'mock', {
           configurable: false,
@@ -714,6 +716,7 @@ function () {
     value: function _generateMock(metadata, callbacks, refs) {
       var _this3 = this;

+      // @ts-ignore
       var mock = this._makeComponent(metadata);

       if (metadata.refID != null) {
@@ -724,9 +727,11 @@ function () {
         var slotMetadata = metadata.members && metadata.members[slot] || {};

         if (slotMetadata.ref != null) {
-          callbacks.push(function () {
-            return mock[slot] = refs[slotMetadata.ref];
-          });
+          callbacks.push(function (ref) {
+            return function () {
+              return mock[slot] = refs[ref];
+            };
+          }(slotMetadata.ref));
         } else {
           mock[slot] = _this3._generateMock(slotMetadata, callbacks, refs);
         }
@@ -790,9 +795,11 @@ function () {
         metadata.value = component;
         return metadata;
       } else if (type === 'function') {
-        metadata.name = component.name;
+        // @ts-ignore this is a function so it has a name
+        metadata.name = component.name; // @ts-ignore may be a mock

         if (component._isMockFunction === true) {
+          // @ts-ignore may be a mock
           metadata.mockImpl = component.getMockImplementation();
         }
       }
@@ -802,11 +809,12 @@ function () {
       var members = null; // Leave arrays alone

       if (type !== 'array') {
-        if (type !== 'undefined') {
         this._getSlots(component).forEach(function (slot) {
-            if (type === 'function' && component._isMockFunction === true && slot.match(/^mock/)) {
+          if (type === 'function' && // @ts-ignore may be a mock
+          component._isMockFunction === true && slot.match(/^mock/)) {
             return;
-            }
+          } // @ts-ignore implicit 'any' type because type '{}' has no index signature
+

           var slotMetadata = _this4.getMetadata(component[slot], refs);

@@ -819,7 +827,6 @@ function () {
           }
         });
       }
-      }

       if (members) {
         metadata.members = members;
@@ -864,13 +871,15 @@ function () {
       if (!this.isMockFunction(original)) {
         if (typeof original !== 'function') {
           throw new Error('Cannot spy the ' + methodName + ' property because it is not a function; ' + this._typeOf(original) + ' given instead');
-        }
+        } // @ts-ignore overriding original method with a Mock
+

         object[methodName] = this._makeComponent({
           type: 'function'
         }, function () {
           object[methodName] = original;
-        });
+        }); // @ts-ignore original method is now a Mock
+
         object[methodName].mockImplementation(function () {
           return original.apply(this, arguments);
         });
@@ -925,12 +934,15 @@ function () {
         descriptor[accessType] = this._makeComponent({
           type: 'function'
         }, function () {
-          // $FlowFixMe
-          descriptor[accessType] = original; // $FlowFixMe
+          if (!descriptor) {
+            return;
+          }

+          descriptor[accessType] = original;
           Object.defineProperty(obj, propertyName, descriptor);
         });
         descriptor[accessType].mockImplementation(function () {
+          // @ts-ignore
           return original.apply(this, arguments);
         });
       }

Test plan

Green CI

@@ -867,19 +1053,23 @@ class ModuleMockerClass {
}

descriptor[accessType] = this._makeComponent({type: 'function'}, () => {
// $FlowFixMe
if (!descriptor) {
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we're in a closure so technically this can be altered, but will it really?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm fine keeping the ignores - I think people would have complained by now if this was actually an issue?

// Leave arrays alone
if (type !== 'array') {
if (type !== 'undefined') {
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we check and bail on 'undefined' earlier so TS told me I can remove it

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎉

Copy link
Member

@SimenB SimenB left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Wooo, this is awesome! 😀

the module.exports at the bottom must be just export so TS generates the correct typings.
Also, please add types to package.json

packages/jest-mock/src/__tests__/index.test.ts Outdated Show resolved Hide resolved
@thymikee
Copy link
Collaborator Author

the module.exports at the bottom must be just export so TS generates the correct typings

I didn't want to do that, because it changes public API of jest-mock. You think it makes sense to do it now? I pushed the change anyway for now and updated the build diff

@SimenB SimenB added this to the TypeScript Migration milestone Feb 10, 2019
@codecov-io
Copy link

codecov-io commented Feb 10, 2019

Codecov Report

Merging #7847 into master will decrease coverage by 0.97%.
The diff coverage is n/a.

Impacted file tree graph

@@            Coverage Diff             @@
##           master    #7847      +/-   ##
==========================================
- Coverage   63.63%   62.66%   -0.98%     
==========================================
  Files         201      200       -1     
  Lines        7922     7590     -332     
  Branches        6        5       -1     
==========================================
- Hits         5041     4756     -285     
+ Misses       2879     2832      -47     
  Partials        2        2

Continue to review full report at Codecov.

Legend - Click here to learn more
Δ = absolute <relative> (impact), ø = not affected, ? = missing data
Powered by Codecov. Last update 842f389...e2f94db. Read the comment docs.

packages/jest-mock/package.json Show resolved Hide resolved
packages/jest-mock/tsconfig.json Outdated Show resolved Hide resolved
Copy link
Member

@SimenB SimenB left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If you feel up to it, could you fix the typing of ModuleMocker in jest-util (and update references there)?

https://github.com/facebook/jest/blob/842f38980d6d4f05a5c86afacdbde11f8b28bd0b/packages/jest-util/src/FakeTimers.ts#L8-L11

Probably type ModuleMocker = typeof import('jest-mock');, haven't tested

mockClear(): void;
mockReset(): void;
mockRestore(): void;
mockImplementation(fn: (...args: Y) => T): Mock<T, Y>;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we can make these return types this to be more accurate (and shorter)?

this._moduleMocker.fn().mockImplementation(impl);

// TODO: add better typings; these are mocks, but typed as regular timers
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

the two comments are connected. cc @SimenB

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I wanna remove the autospying anyways (I've removed it in the Lolex implementation)

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

However, we should be able to infer the type of the function passed in (can do later)

@SimenB SimenB merged commit 100b033 into jestjs:master Feb 10, 2019
@SimenB
Copy link
Member

SimenB commented Feb 10, 2019

Thoughts on making stuff private:

diff --git c/packages/jest-mock/src/index.ts w/packages/jest-mock/src/index.ts
index 9e6450e09..b118e9694 100644
--- c/packages/jest-mock/src/index.ts
+++ w/packages/jest-mock/src/index.ts
@@ -328,12 +328,12 @@ function isReadonlyProp(object: any, prop: string): boolean {
 }
 
 class ModuleMockerClass {
-  _environmentGlobal: Global;
-  _mockState: WeakMap<Mock<any, any>, MockFunctionState<any, any>>;
-  _mockConfigRegistry: WeakMap<Function, MockFunctionConfig>;
-  _spyState: Set<() => void>;
+  private _environmentGlobal: Global;
+  private _mockState: WeakMap<Mock<any, any>, MockFunctionState<any, any>>;
+  private _mockConfigRegistry: WeakMap<Function, MockFunctionConfig>;
+  private _spyState: Set<() => void>;
   ModuleMocker: typeof ModuleMockerClass;
-  _invocationCallCounter: number;
+  private _invocationCallCounter: number;
 
   /**
    * @see README.md
@@ -349,7 +349,7 @@ class ModuleMockerClass {
     this._invocationCallCounter = 1;
   }
 
-  _getSlots(object?: Object): Array<string> {
+  private _getSlots(object?: Object): Array<string> {
     if (!object) {
       return [];
     }
@@ -396,7 +396,9 @@ class ModuleMockerClass {
     return Array.from(slots);
   }
 
-  _ensureMockConfig<T, Y extends unknown[]>(f: Mock<T, Y>): MockFunctionConfig {
+  private _ensureMockConfig<T, Y extends unknown[]>(
+    f: Mock<T, Y>,
+  ): MockFunctionConfig {
     let config = this._mockConfigRegistry.get(f);
     if (!config) {
       config = this._defaultMockConfig();
@@ -405,7 +407,7 @@ class ModuleMockerClass {
     return config;
   }
 
-  _ensureMockState<T, Y extends unknown[]>(
+  private _ensureMockState<T, Y extends unknown[]>(
     f: Mock<T, Y>,
   ): MockFunctionState<T, Y> {
     let state = this._mockState.get(f);
@@ -416,7 +418,7 @@ class ModuleMockerClass {
     return state;
   }
 
-  _defaultMockConfig(): MockFunctionConfig {
+  private _defaultMockConfig(): MockFunctionConfig {
     return {
       defaultReturnValue: undefined,
       isReturnValueLastSet: false,
@@ -427,7 +429,7 @@ class ModuleMockerClass {
     };
   }
 
-  _defaultMockState<T, Y extends unknown[]>(): MockFunctionState<T, Y> {
+  private _defaultMockState<T, Y extends unknown[]>(): MockFunctionState<T, Y> {
     return {
       calls: [],
       instances: [],
@@ -436,19 +438,19 @@ class ModuleMockerClass {
     };
   }
 
-  _makeComponent<T, Y extends unknown[]>(
+  private _makeComponent<T, Y extends unknown[]>(
     metadata: Mocks.MockFunctionMetadata<T, Y, 'object'>,
     restore?: () => void,
   ): Object;
-  _makeComponent<T, Y extends unknown[]>(
+  private _makeComponent<T, Y extends unknown[]>(
     metadata: Mocks.MockFunctionMetadata<T, Y, 'array'>,
     restore?: () => void,
   ): Array<unknown>;
-  _makeComponent<T, Y extends unknown[]>(
+  private _makeComponent<T, Y extends unknown[]>(
     metadata: Mocks.MockFunctionMetadata<T, Y, 'regexp'>,
     restore?: () => void,
   ): RegExp;
-  _makeComponent<T, Y extends unknown[]>(
+  private _makeComponent<T, Y extends unknown[]>(
     metadata: Mocks.MockFunctionMetadata<
       T,
       Y,
@@ -456,11 +458,11 @@ class ModuleMockerClass {
     >,
     restore?: () => void,
   ): T;
-  _makeComponent<T, Y extends unknown[]>(
+  private _makeComponent<T, Y extends unknown[]>(
     metadata: Mocks.MockFunctionMetadata<T, Y, 'function'>,
     restore?: () => void,
   ): Mock<T, Y>;
-  _makeComponent<T, Y extends unknown[]>(
+  private _makeComponent<T, Y extends unknown[]>(
     metadata: Mocks.MockFunctionMetadata<T, Y>,
     restore?: () => void,
   ): Object | Array<unknown> | RegExp | T | undefined | Mock<T, Y> {
@@ -706,7 +708,7 @@ class ModuleMockerClass {
     }
   }
 
-  _createMockFunction<T, Y extends unknown[]>(
+  private _createMockFunction<T, Y extends unknown[]>(
     metadata: Mocks.MockFunctionMetadata<T, Y>,
     mockConstructor: Function,
   ): Function {
@@ -766,7 +768,7 @@ class ModuleMockerClass {
     return createConstructor(mockConstructor);
   }
 
-  _generateMock<T, Y extends unknown[]>(
+  private _generateMock<T, Y extends unknown[]>(
     metadata: Mocks.MockFunctionMetadata<T, Y>,
     callbacks: Array<Function>,
     refs: {
@@ -973,7 +975,7 @@ class ModuleMockerClass {
     return object[methodName];
   }
 
-  _spyOnProperty<T extends {}, M extends keyof T>(
+  private _spyOnProperty<T extends {}, M extends keyof T>(
     obj: T,
     propertyName: M,
     accessType: 'get' | 'set' = 'get',
@@ -1060,7 +1062,7 @@ class ModuleMockerClass {
     this._spyState = new Set();
   }
 
-  _typeOf(value: any): string {
+  private _typeOf(value: any): string {
     return value == null ? '' + value : typeof value;
   }
 }

Results in this definition file:

diff --git i/packages/jest-mock/build/index.d.ts w/packages/jest-mock/build/index.d.ts
index e6ae9a0cb..23cb93a44 100644
--- i/packages/jest-mock/build/index.d.ts
+++ w/packages/jest-mock/build/index.d.ts
@@ -39,14 +39,6 @@ declare type MockFunctionState<T, Y extends unknown[]> = {
      */
     results: Array<MockFunctionResult>;
 };
-declare type MockFunctionConfig = {
-    isReturnValueLastSet: boolean;
-    defaultReturnValue: unknown;
-    mockImpl: Function | undefined;
-    mockName: string;
-    specificReturnValues: Array<unknown>;
-    specificMockImpls: Array<Function>;
-};
 interface Mock<T, Y extends unknown[] = unknown[]> extends Function, MockInstance<T, Y> {
     new (...args: Y): T;
     (...args: Y): T;
@@ -76,32 +68,26 @@ interface MockInstance<T, Y extends unknown[]> {
     mockRejectedValueOnce(value: T): this;
 }
 declare class ModuleMockerClass {
-    _environmentGlobal: Global;
-    _mockState: WeakMap<Mock<any, any>, MockFunctionState<any, any>>;
-    _mockConfigRegistry: WeakMap<Function, MockFunctionConfig>;
-    _spyState: Set<() => void>;
+    private _environmentGlobal;
+    private _mockState;
+    private _mockConfigRegistry;
+    private _spyState;
     ModuleMocker: typeof ModuleMockerClass;
-    _invocationCallCounter: number;
+    private _invocationCallCounter;
     /**
      * @see README.md
      * @param global Global object of the test environment, used to create
      * mocks
      */
     constructor(global: Global);
-    _getSlots(object?: Object): Array<string>;
-    _ensureMockConfig<T, Y extends unknown[]>(f: Mock<T, Y>): MockFunctionConfig;
-    _ensureMockState<T, Y extends unknown[]>(f: Mock<T, Y>): MockFunctionState<T, Y>;
-    _defaultMockConfig(): MockFunctionConfig;
-    _defaultMockState<T, Y extends unknown[]>(): MockFunctionState<T, Y>;
-    _makeComponent<T, Y extends unknown[]>(metadata: Mocks.MockFunctionMetadata<T, Y, 'object'>, restore?: () => void): Object;
-    _makeComponent<T, Y extends unknown[]>(metadata: Mocks.MockFunctionMetadata<T, Y, 'array'>, restore?: () => void): Array<unknown>;
-    _makeComponent<T, Y extends unknown[]>(metadata: Mocks.MockFunctionMetadata<T, Y, 'regexp'>, restore?: () => void): RegExp;
-    _makeComponent<T, Y extends unknown[]>(metadata: Mocks.MockFunctionMetadata<T, Y, 'constant' | 'collection' | 'null' | 'undefined'>, restore?: () => void): T;
-    _makeComponent<T, Y extends unknown[]>(metadata: Mocks.MockFunctionMetadata<T, Y, 'function'>, restore?: () => void): Mock<T, Y>;
-    _createMockFunction<T, Y extends unknown[]>(metadata: Mocks.MockFunctionMetadata<T, Y>, mockConstructor: Function): Function;
-    _generateMock<T, Y extends unknown[]>(metadata: Mocks.MockFunctionMetadata<T, Y>, callbacks: Array<Function>, refs: {
-        [key: string]: Object | Array<unknown> | RegExp | T | undefined | Mock<T, Y>;
-    }): Mock<T, Y>;
+    private _getSlots;
+    private _ensureMockConfig;
+    private _ensureMockState;
+    private _defaultMockConfig;
+    private _defaultMockState;
+    private _makeComponent;
+    private _createMockFunction;
+    private _generateMock;
     /**
      * @see README.md
      * @param _metadata Metadata for the mock in the schema returned by the
@@ -118,11 +104,11 @@ declare class ModuleMockerClass {
     spyOn<T extends {}, M extends keyof T>(object: T, methodName: M, accessType: 'get'): SpyInstance<T[M], []>;
     spyOn<T extends {}, M extends keyof T>(object: T, methodName: M, accessType: 'set'): SpyInstance<void, [T[M]]>;
     spyOn<T extends {}, M extends keyof T>(object: T, methodName: M): T[M] extends (...args: any[]) => any ? SpyInstance<ReturnType<T[M]>, ArgsType<T[M]>> : never;
-    _spyOnProperty<T extends {}, M extends keyof T>(obj: T, propertyName: M, accessType?: 'get' | 'set'): Mock<T>;
+    private _spyOnProperty;
     clearAllMocks(): void;
     resetAllMocks(): void;
     restoreAllMocks(): void;
-    _typeOf(value: any): string;
+    private _typeOf;
 }
 declare const _default: ModuleMockerClass;
 export = _default;

@thymikee
Copy link
Collaborator Author

I didn't want to make this diff any bigger but this should look like you proposed, way better

@github-actions
Copy link

This pull request has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.
Please note this issue tracker is not a help forum. We recommend using StackOverflow or our discord channel for questions.

@github-actions github-actions bot locked as resolved and limited conversation to collaborators May 11, 2021
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

Successfully merging this pull request may close these issues.

5 participants