Skip to content

Commit 9c175fc

Browse files
authored
Fix dynamic import to work with jest
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)
1 parent 70ada01 commit 9c175fc

File tree

1 file changed

+15
-6
lines changed

1 file changed

+15
-6
lines changed

packages/openapi-framework/index.ts

+15-6
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import os from 'node:os';
12
import fsRoutes from 'fs-routes';
23
import OpenAPIDefaultSetter from 'openapi-default-setter';
34
import OpenAPIRequestCoercer from 'openapi-request-coercer';
@@ -230,12 +231,20 @@ export default class OpenAPIFramework implements IOpenAPIFramework {
230231
})
231232
.map(async (fsRoutesItem) => {
232233
routesCheckMap[fsRoutesItem.route] = true;
233-
// There are two cases to distinguish:
234-
// - file is a CommonJS script, and `module.export` appears
235-
// as `default` property
236-
// - file is a ECMAScript module, and `export default` appears
237-
// at top-level
238-
const imported = await import(`file://${fsRoutesItem.path}`);
234+
/**
235+
* There are a few cases to distinguish:
236+
* - file is a CommonJS script, and `module.export` appears
237+
* as `default` property.
238+
* - file is a ECMAScript module, and `export default` appears
239+
* at top-level.
240+
* - OS is Windows needs absolute path while others support
241+
* relative paths.
242+
*/
243+
let importPath = fsRoutesItem.path;
244+
if (os.type().includes('Windows')) {
245+
importPath = `file://${importPath}`;
246+
}
247+
const imported = await import(importPath);
239248
return {
240249
path: fsRoutesItem.route,
241250
module: imported.default ?? imported,

0 commit comments

Comments
 (0)