diff --git a/CHANGELOG.md b/CHANGELOG.md index 07c630555d7e..30e02ef4c957 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -21,6 +21,7 @@ - `[jest-resolve]` Update `resolve` to a version using native `realpath`, which is faster than the default JS implementation ([#9872](https://github.com/facebook/jest/pull/9872)) - `[jest-resolve]` Pass custom cached `realpath` function to `resolve` ([#9873](https://github.com/facebook/jest/pull/9873)) +- `[jest-runtime]` Add `teardown` method to clear any caches when tests complete ([#9906](https://github.com/facebook/jest/pull/9906)) ## 25.4.0 diff --git a/packages/jest-runner/src/runTest.ts b/packages/jest-runner/src/runTest.ts index dd8735be8b57..80c5ae5dc067 100644 --- a/packages/jest-runner/src/runTest.ts +++ b/packages/jest-runner/src/runTest.ts @@ -300,6 +300,8 @@ async function runTestInternal( }); } finally { await environment.teardown(); + // TODO: this function might be missing, remove ? in Jest 26 + runtime.teardown?.(); sourcemapSupport.resetRetrieveHandlers(); } diff --git a/packages/jest-runtime/src/index.ts b/packages/jest-runtime/src/index.ts index ecb2d25f3ef8..59b48d66bc04 100644 --- a/packages/jest-runtime/src/index.ts +++ b/packages/jest-runtime/src/index.ts @@ -718,12 +718,17 @@ class Runtime { try { fn(); } finally { + // might be cleared within the callback + this._isolatedModuleRegistry?.clear(); + this._isolatedMockRegistry?.clear(); this._isolatedModuleRegistry = null; this._isolatedMockRegistry = null; } } resetModules(): void { + this._isolatedModuleRegistry?.clear(); + this._isolatedMockRegistry?.clear(); this._isolatedModuleRegistry = null; this._isolatedMockRegistry = null; this._mockRegistry.clear(); @@ -833,6 +838,29 @@ class Runtime { this._moduleMocker.clearAllMocks(); } + teardown(): void { + this.restoreAllMocks(); + this.resetAllMocks(); + this.resetModules(); + + this._internalModuleRegistry.clear(); + this._mockFactories = {}; + this._mockMetaDataCache = {}; + this._shouldMockModuleCache = {}; + this._shouldUnmockTransitiveDependenciesCache = {}; + this._transitiveShouldMock = {}; + this._virtualMocks = {}; + this._cacheFS = {}; + + this._sourceMapRegistry = {}; + + this._fileTransforms.clear(); + this.jestObjectCaches.clear(); + + this._v8CoverageResult = []; + this._moduleImplementation = undefined; + } + private _resolveModule(from: Config.Path, to?: string) { return to ? this._resolver.resolveModule(from, to) : from; }