Skip to content

Commit

Permalink
Fix dynamic import to work with jest
Browse files Browse the repository at this point in the history
When using jest this code gets transpiled to `require` and the file URL syntax of the import is not supported and breaks the testing environment.  This change only uses file URL import syntax on windows machines.  This fixes our tests and is still supported on linux and mac operating systems.

I think windows is definitely in the minority here and we should not optimize for it.  Furthermore, I believe using a UNC path would be a better solution outright but I cannot test because I don't have a window machine at hand.

Why not just use jest's `--experimental-vm-modules` flag? Glad you asked.  Because of this [jest bug](jestjs/jest#11434 (comment)) which is caused by this [node bug](nodejs/node#37648) which is ultimately caused by this [v8 bug](https://issues.chromium.org/issues/40784051)
  • Loading branch information
coryasilva authored Sep 10, 2024
1 parent 70ada01 commit 9c175fc
Showing 1 changed file with 15 additions and 6 deletions.
21 changes: 15 additions & 6 deletions packages/openapi-framework/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import os from 'node:os';
import fsRoutes from 'fs-routes';
import OpenAPIDefaultSetter from 'openapi-default-setter';
import OpenAPIRequestCoercer from 'openapi-request-coercer';
Expand Down Expand Up @@ -230,12 +231,20 @@ export default class OpenAPIFramework implements IOpenAPIFramework {
})
.map(async (fsRoutesItem) => {
routesCheckMap[fsRoutesItem.route] = true;
// There are two cases to distinguish:
// - file is a CommonJS script, and `module.export` appears
// as `default` property
// - file is a ECMAScript module, and `export default` appears
// at top-level
const imported = await import(`file://${fsRoutesItem.path}`);
/**
* There are a few cases to distinguish:
* - file is a CommonJS script, and `module.export` appears
* as `default` property.
* - file is a ECMAScript module, and `export default` appears
* at top-level.
* - OS is Windows needs absolute path while others support
* relative paths.
*/
let importPath = fsRoutesItem.path;
if (os.type().includes('Windows')) {
importPath = `file://${importPath}`;
}
const imported = await import(importPath);
return {
path: fsRoutesItem.route,
module: imported.default ?? imported,
Expand Down

0 comments on commit 9c175fc

Please sign in to comment.