Skip to content

Commit

Permalink
Fight against unresolved promises in jest (relates #65)
Browse files Browse the repository at this point in the history
With this change, the rate of promise failures is already lowered from
ca. 1/2 to 1/50, but from time to time, the bug still appears. Sigh ...
  • Loading branch information
LinqLover committed Jun 22, 2021
1 parent 57f7a16 commit 472d90f
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 9 deletions.
23 changes: 21 additions & 2 deletions src/references.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import tqdm from 'ntqdm'
import path from 'path'

import { getCacheDirectory } from './npm-deps'
import dynamicImport from "./utils/dynamic-import"
import rex from './utils/rex'


Expand Down Expand Up @@ -117,6 +116,17 @@ class PackageReferenceSearcher {

const identifierPattern = /[\p{L}\p{Nl}$_][\p{L}\p{Nl}$\p{Mn}\p{Mc}\p{Nd}\p{Pc}]*/u

/**
* Workaround for https://github.com/microsoft/TypeScript/issues/43329.
*
* TypeScript will always try to replace dynamic imports with `requires` which doesn't work for importing ESM from CJS.
* We work around by "hiding" our dynamic import in a Function constructor (terrible...).
*
* In particular, we must not extract this call into a separate module.
* This would result in sporadic unresolved promises in the jest environment.
* See #65.
*/
const dynamicImport = new Function('moduleName', 'return import(moduleName)')
const escapeRegexp = (await dynamicImport('escape-string-regexp')).default
const requirePattern = rex`
(?<alias> ${identifierPattern} ) \s*
Expand Down Expand Up @@ -186,9 +196,18 @@ class PackageReferenceSearcher {
// Truly awful hack! There are a few things going on here:
// - Jest (or something) can't find parse-imports by just importing its package name
// no matter what. Just give it the path to the src/index.js file
// - See the comment in dynamicImport
// - Workaround for https://github.com/microsoft/TypeScript/issues/43329.
//
// TypeScript will always try to replace dynamic imports with `requires` which doesn't work for importing ESM from CJS.
// We work around by "hiding" our dynamic import in a Function constructor (terrible...).
//
// In particular, we must not extract this call into a separate module.
// This would result in sporadic unresolved promises in the jest environment.
// See #65.
//
// - All of this required jest@next, ts-jest@next, AND `NODE_OPTIONS=--experimental-vm-modules`
const parseImportsIndexPath = path.join(path.dirname(__dirname), 'node_modules/parse-imports/src/index.js')
const dynamicImport = new Function('moduleName', 'return import(moduleName)')
const parseImports = (await dynamicImport(parseImportsIndexPath)).default

return await parseImports(source)
Expand Down
7 changes: 0 additions & 7 deletions src/utils/dynamic-import.ts

This file was deleted.

0 comments on commit 472d90f

Please sign in to comment.