From 9c175fc904c8a69182ec157979075b334ac7d417 Mon Sep 17 00:00:00 2001 From: Cory Silva <2672972+coryasilva@users.noreply.github.com> Date: Tue, 10 Sep 2024 10:26:41 -0700 Subject: [PATCH] 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](https://github.com/jestjs/jest/issues/11434#issuecomment-1410445848) which is caused by this [node bug](https://github.com/nodejs/node/issues/37648) which is ultimately caused by this [v8 bug](https://issues.chromium.org/issues/40784051) --- packages/openapi-framework/index.ts | 21 +++++++++++++++------ 1 file changed, 15 insertions(+), 6 deletions(-) diff --git a/packages/openapi-framework/index.ts b/packages/openapi-framework/index.ts index ab53a186..d87a4ff5 100644 --- a/packages/openapi-framework/index.ts +++ b/packages/openapi-framework/index.ts @@ -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'; @@ -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,