-
-
Notifications
You must be signed in to change notification settings - Fork 6.5k
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
Add jest.isolateModules
for scoped module initialization
#6701
Changes from 8 commits
93a11a1
1f86b12
65e426e
68d4e40
927773d
fffd74f
8c6910d
9e4c58c
c6ca84a
59fb053
6eab501
a829797
380e9c6
8c9e2d0
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -551,6 +551,21 @@ Default: `false` | |
|
||
By default, each test file gets its own independent module registry. Enabling `resetModules` goes a step further and resets the module registry before running each individual test. This is useful to isolate modules for every test so that local module state doesn't conflict between tests. This can be done programmatically using [`jest.resetModules()`](#jest-resetmodules). | ||
|
||
### `isolateModules` [boolean] | ||
|
||
Default: `false` | ||
|
||
`isolateModules` goes a step further than `resetModules` and creates a sanbox registry for the modules that are loaded inside the callback function. This is useful to isolate modules for every test so that local module state doesn't conflict between tests. This can be done programmatically using [`jest.isolateModules()`](#jest-isolatemodules). | ||
|
||
```js | ||
let myModule; | ||
jest.isolateModules(() => { | ||
myModule = require('myModule'); | ||
}); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I think we should move the example to https://jestjs.io/docs/en/jest-object (and fix the link to There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Good point, I think it should only live in jest-object. This was my bad. |
||
|
||
let otherCopyOfMyModule = require('myModule'); | ||
``` | ||
|
||
### `resolver` [string] | ||
|
||
Default: `undefined` | ||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -175,3 +175,110 @@ it('unmocks modules in config.unmockedModulePathPatterns for tests with automock | |
const moduleData = nodeModule(); | ||
expect(moduleData.isUnmocked()).toBe(true); | ||
})); | ||
|
||
describe('resetModules', () => { | ||
it('resets all the modules', () => | ||
createRuntime(__filename, { | ||
moduleNameMapper, | ||
}).then(runtime => { | ||
let exports = runtime.requireModuleOrMock( | ||
runtime.__mockRootPath, | ||
'ModuleWithState', | ||
); | ||
expect(exports.getState()).toBe(1); | ||
exports.increment(); | ||
expect(exports.getState()).toBe(2); | ||
runtime.resetModules(); | ||
exports = runtime.requireModuleOrMock( | ||
runtime.__mockRootPath, | ||
'ModuleWithState', | ||
); | ||
expect(exports.getState()).toBe(1); | ||
})); | ||
}); | ||
|
||
describe('isolateModules', () => { | ||
it('resets all modules after the block', async () => | ||
createRuntime(__filename, { | ||
moduleNameMapper, | ||
}).then(runtime => { | ||
let exports; | ||
runtime.isolateModules(() => { | ||
exports = runtime.requireModuleOrMock( | ||
runtime.__mockRootPath, | ||
'ModuleWithState', | ||
); | ||
expect(exports.getState()).toBe(1); | ||
exports.increment(); | ||
expect(exports.getState()).toBe(2); | ||
}); | ||
|
||
exports = runtime.requireModuleOrMock( | ||
runtime.__mockRootPath, | ||
'ModuleWithState', | ||
); | ||
expect(exports.getState()).toBe(1); | ||
})); | ||
|
||
it('cannot nest isolateModules blocks', async () => | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Async? |
||
createRuntime(__filename, { | ||
moduleNameMapper, | ||
}).then(runtime => { | ||
expect(() => { | ||
runtime.isolateModules(() => { | ||
runtime.isolateModules(() => {}); | ||
}); | ||
}).toThrowError( | ||
'isolateModules cannot be nested inside another isolateModules.', | ||
); | ||
})); | ||
|
||
it('can call resetModules within a isolateModules block', async () => | ||
createRuntime(__filename, { | ||
moduleNameMapper, | ||
}).then(runtime => { | ||
let exports; | ||
runtime.isolateModules(() => { | ||
exports = runtime.requireModuleOrMock( | ||
runtime.__mockRootPath, | ||
'ModuleWithState', | ||
); | ||
expect(exports.getState()).toBe(1); | ||
|
||
exports.increment(); | ||
runtime.resetModules(); | ||
|
||
exports = runtime.requireModuleOrMock( | ||
runtime.__mockRootPath, | ||
'ModuleWithState', | ||
); | ||
expect(exports.getState()).toBe(1); | ||
}); | ||
|
||
exports = runtime.requireModuleOrMock( | ||
runtime.__mockRootPath, | ||
'ModuleWithState', | ||
); | ||
expect(exports.getState()).toBe(1); | ||
})); | ||
|
||
describe('can use isolateModules from a beforeEach block', () => { | ||
let exports; | ||
beforeEach(() => { | ||
jest.isolateModules(() => { | ||
exports = require('./test_root/ModuleWithState'); | ||
}); | ||
}); | ||
|
||
it('can use the required module from beforeEach and re-require it', () => { | ||
expect(exports.getState()).toBe(1); | ||
exports.increment(); | ||
expect(exports.getState()).toBe(2); | ||
|
||
exports = require('./test_root/ModuleWithState'); | ||
expect(exports.getState()).toBe(1); | ||
exports.increment(); | ||
expect(exports.getState()).toBe(2); | ||
}); | ||
}); | ||
}); |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,16 @@ | ||
/** | ||
* Copyright (c) 2014-present, Facebook, Inc. All rights reserved. | ||
* | ||
* This source code is licensed under the MIT license found in the | ||
* LICENSE file in the root directory of this source tree. | ||
* | ||
* @providesModule ModuleWithState | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. We've cleaned out providesModule from master |
||
*/ | ||
|
||
let state = 1; | ||
|
||
export const increment = () => { | ||
state += 1; | ||
}; | ||
|
||
export const getState = () => state; |
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -96,7 +96,9 @@ class Runtime { | |
_mockFactories: {[key: string]: () => any, __proto__: null}; | ||
_mockMetaDataCache: {[key: string]: MockFunctionMetadata, __proto__: null}; | ||
_mockRegistry: {[key: string]: any, __proto__: null}; | ||
_sandboxMockRegistry: ?{[key: string]: any, __proto__: null}; | ||
_moduleMocker: ModuleMocker; | ||
_sandboxModuleRegistry: ?ModuleRegistry; | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I think There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 👍 I like it way better! |
||
_moduleRegistry: ModuleRegistry; | ||
_needsCoverageMapped: Set<string>; | ||
_resolver: Resolver; | ||
|
@@ -131,6 +133,7 @@ class Runtime { | |
this._mockFactories = Object.create(null); | ||
this._mockRegistry = Object.create(null); | ||
this._moduleMocker = this._environment.moduleMocker; | ||
this._sandboxModuleRegistry = null; | ||
this._moduleRegistry = Object.create(null); | ||
this._needsCoverageMapped = new Set(); | ||
this._resolver = resolver; | ||
|
@@ -282,11 +285,6 @@ class Runtime { | |
); | ||
let modulePath; | ||
|
||
const moduleRegistry = | ||
!options || !options.isInternalModule | ||
? this._moduleRegistry | ||
: this._internalModuleRegistry; | ||
|
||
// Some old tests rely on this mocking behavior. Ideally we'll change this | ||
// to be more explicit. | ||
const moduleResource = moduleName && this._resolver.getModule(moduleName); | ||
|
@@ -310,6 +308,18 @@ class Runtime { | |
modulePath = this._resolveModule(from, moduleName); | ||
} | ||
|
||
let moduleRegistry; | ||
|
||
if (!options || !options.isInternalModule) { | ||
if (this._moduleRegistry[modulePath] || !this._sandboxModuleRegistry) { | ||
moduleRegistry = this._moduleRegistry; | ||
} else { | ||
moduleRegistry = this._sandboxModuleRegistry; | ||
} | ||
} else { | ||
moduleRegistry = this._internalModuleRegistry; | ||
} | ||
|
||
if (!moduleRegistry[modulePath]) { | ||
// We must register the pre-allocated module object first so that any | ||
// circular dependencies that may arise while evaluating the module can | ||
|
@@ -351,12 +361,16 @@ class Runtime { | |
moduleName, | ||
); | ||
|
||
if (this._mockRegistry[moduleID]) { | ||
if (this._sandboxMockRegistry && this._sandboxMockRegistry[moduleID]) { | ||
return this._sandboxMockRegistry[moduleID]; | ||
} else if (this._mockRegistry[moduleID]) { | ||
return this._mockRegistry[moduleID]; | ||
} | ||
|
||
const mockRegistry = this._sandboxMockRegistry || this._mockRegistry; | ||
|
||
if (moduleID in this._mockFactories) { | ||
return (this._mockRegistry[moduleID] = this._mockFactories[moduleID]()); | ||
return (mockRegistry[moduleID] = this._mockFactories[moduleID]()); | ||
} | ||
|
||
let manualMock = this._resolver.getMockModule(from, moduleName); | ||
|
@@ -400,15 +414,15 @@ class Runtime { | |
|
||
// Only include the fromPath if a moduleName is given. Else treat as root. | ||
const fromPath = moduleName ? from : null; | ||
this._execModule(localModule, undefined, this._mockRegistry, fromPath); | ||
this._mockRegistry[moduleID] = localModule.exports; | ||
this._execModule(localModule, undefined, mockRegistry, fromPath); | ||
mockRegistry[moduleID] = localModule.exports; | ||
localModule.loaded = true; | ||
} else { | ||
// Look for a real module to generate an automock from | ||
this._mockRegistry[moduleID] = this._generateMock(from, moduleName); | ||
mockRegistry[moduleID] = this._generateMock(from, moduleName); | ||
} | ||
|
||
return this._mockRegistry[moduleID]; | ||
return mockRegistry[moduleID]; | ||
} | ||
|
||
requireModuleOrMock(from: Path, moduleName: string) { | ||
|
@@ -419,10 +433,24 @@ class Runtime { | |
} | ||
} | ||
|
||
isolateModules(fn: () => void) { | ||
if (this._sandboxModuleRegistry || this._sandboxMockRegistry) { | ||
throw new Error( | ||
'isolateModules cannot be nested inside another isolateModules.', | ||
); | ||
} | ||
this._sandboxModuleRegistry = Object.create(null); | ||
this._sandboxMockRegistry = Object.create(null); | ||
fn(); | ||
this._sandboxModuleRegistry = null; | ||
this._sandboxMockRegistry = null; | ||
} | ||
|
||
resetModules() { | ||
this._sandboxModuleRegistry = null; | ||
this._sandboxMockRegistry = null; | ||
this._mockRegistry = Object.create(null); | ||
this._moduleRegistry = Object.create(null); | ||
|
||
if (this._environment && this._environment.global) { | ||
const envGlobal = this._environment.global; | ||
Object.keys(envGlobal).forEach(key => { | ||
|
@@ -434,7 +462,6 @@ class Runtime { | |
globalMock._isMockFunction === true && globalMock.mockClear(); | ||
} | ||
}); | ||
|
||
if (envGlobal.mockClearTimers) { | ||
envGlobal.mockClearTimers(); | ||
} | ||
|
@@ -876,6 +903,10 @@ class Runtime { | |
this.resetModules(); | ||
return jestObject; | ||
}; | ||
const isolateModules = (fn: () => void) => { | ||
this.isolateModules(fn); | ||
return jestObject; | ||
}; | ||
const fn = this._moduleMocker.fn.bind(this._moduleMocker); | ||
const spyOn = this._moduleMocker.spyOn.bind(this._moduleMocker); | ||
|
||
|
@@ -911,6 +942,7 @@ class Runtime { | |
genMockFromModule: (moduleName: string) => | ||
this._generateMock(from, moduleName), | ||
isMockFunction: this._moduleMocker.isMockFunction, | ||
isolateModules, | ||
mock, | ||
requireActual: localRequire.requireActual, | ||
requireMock: localRequire.requireMock, | ||
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Typo: sanbox