jest-node-exports-resolver icon indicating copy to clipboard operation
jest-node-exports-resolver copied to clipboard

findMainPackageJson() doesn't work properly on Windows

Open kasperpawlowski opened this issue 3 years ago • 1 comments

I've just noticed inconsistent behavior of the package. Due to the fact that Windows uses backslash path separator, the directoryName.endsWith(packageName) condition from findMainPackageJson() will never be fulfilled. It seems that the packageName should also have '/' replaced with path.sep, same way it's done for directoryName. Hence, the updated code should look like this:

function findMainPackageJson(entryPath, packageName) {
  entryPath = entryPath.replace(/\//g, path.sep);
  packageName = packageName.replace(/\//g, path.sep); // <--- this line has been added

  let directoryName = path.dirname(entryPath);
  while (directoryName && !directoryName.endsWith(packageName)) {
    const parentDirectoryName = path.resolve(directoryName, "..");

    if (parentDirectoryName === directoryName) break;

    directoryName = parentDirectoryName;
  }

  const suspect = path.resolve(directoryName, "package.json");
  if (fs.existsSync(suspect)) {
    return JSON.parse(fs.readFileSync(suspect).toString());
  }

  return null;
}

kasperpawlowski avatar Jul 21 '22 16:07 kasperpawlowski

Forgot to mention that because of the above, on Windows the following line returns null. https://github.com/k-g-a/jest-node-exports-resolver/blob/d6196002b7b2e70f1cef68e7a6e9a60d77641dc4/index.js#L63

requestPath is defined but findMainPackageJson() returns null which makes the resolver not working properly for a subset of node exports.

kasperpawlowski avatar Jul 21 '22 16:07 kasperpawlowski