feature: jest.isolateModules accept an async function for dynamic import()s
See original GitHub issue🚀 Feature Proposal
Have the ability to pass jest.isolatedModules
an async function, and have it wait for the promise to resolve before cleaning up the isolated module registry.
I think this feature might be kind of tricky, because currently it appears there is at most one isolated module registry in a given runtime, meaning that successive calls to jest.isolatedModules
with async functions (without waiting for each to resolve) would overlap and fail.
Motivation
Right now, jest.isolateModules()
appears to work for static imports only: https://github.com/facebook/jest/blob/v26.4.0/packages/jest-runtime/src/index.ts#L748. But if you use babel-jest
and your modules make use of dynamic import()
s, the finally
block will clean up the isolated modules registry prior to import()
s resolving.
My specific use-case for this feature is in defining a helper function for integration tests, that sets up my entire application—mocking some key dependencies—and returns a reference to the root page component mounted in the jsdom
environment. This entrypoint uses multiple dynamic imports during its initialization. I’d like the helper function to be self-contained, as I can’t make assumptions about how it’s called. It could be called multiple times within a test suite, for example, hence the desire to use isolatedModules
.
Example
async function loadApp() {
document.body.innerHTML = '<div id="#app"></div>' // The mount point required by the entrypoint.
let component
await jest.isolatedModules(async () => { // If passed an async function, `isolatedModules` should likewise return a promise.
jest.doMock('depA', ... )
...
component = await require('path/to/app/entrypoint') // The entrypoint exports a promise resolving to the root component instance, once all initialization is complete.
})
return component
}
test('App mounts to #app', async () => {
const vm = await loadApp()
const mountpoint = document.querySelector('#app')
expect(vm.el).toBe(mountpoint)
})
Issue Analytics
- State:
- Created 3 years ago
- Reactions:26
- Comments:5
Top GitHub Comments
is this something that is still looked into? having async support for isolateModules would be great. Each of my projects has the following patch so that I can use it with
import()
sThe change is pretty straightforward, do you think we can incorporate this into the codebase? I can make a proper PR with test coverage and stuff
this of course forces you to await
isolateModules
in your code if you want to access thejestObject
but I think it’s ok. if it’s not ok, however, we can make two different top-level functionsisolateModules
andisolateModulesAsync
that will delegate to the same internalisolaleModules
implementationYeah, this (or something similar) is needed for proper ESM support