Giter Club home page Giter Club logo

jest-node-exports-resolver's People

Contributors

exarus avatar ezzatron avatar k-g-a avatar piranna avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

jest-node-exports-resolver's Issues

Doesn't work with `ws` module

When importing ws module, it gets the CommonJS version instead of the ESM one, although it has defined both main and exports fields. This last one has conditions for both import and require, in case is this the issue.

Doesn't seem to work with @firebase/auth

Maybe I'm missing something, but I'm still having issues with firebase

Jest encountered an unexpected token

Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.

node_modules/firebase/auth/dist/index.esm.js:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){export * from '@firebase/auth';
                                                                                      ^^^^^^

    SyntaxError: Unexpected token 'export'

    > 1 | import { getAuth } from 'firebase/auth';
        | ^

Since 1.1.3 'Cannot use import statement outside a module'

Thank you very much for this library. It worked perfectly on version 1.1.2. However, on version 1.1.3 I get the error SyntaxError: Cannot use import statement outside a module when using the firebase package.

My node app uses require but this is somehow getting changed to import.

I made a minimal example at https://github.com/yaakovfeldman/jest-issue

Running npm run test with version 1.1.2 should produce no issues (except for jest complaining that the test suite contains no tests).

Updating to version 1.1.3 produces:

Details:

    C:\Users\yfeld\Code\school databases\jest-issue\node_modules\firebase\app\dist\index.esm.js:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){import { registerVersion } from '@firebase/app';
                                                                                      ^^^^^^

    SyntaxError: Cannot use import statement outside a module

      1 | const express = require('express')
    > 2 | const { initializeApp } = require('firebase/app');
        |                           ^
      3 | //const admin = require('firebase-admin');
      4 |
      5 | const app = express()

      at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1728:14)
      at Object.<anonymous> (app.js:2:27)

Test Suites: 1 failed, 1 total

findMainPackageJson() doesn't work properly on Windows

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;
}

Not working accessing files in scoped packages

When accessing to a file in a package without exports field (using main instead), it can't find them. Something like @mafalda/fsset/waiting.js resolves to null instead of the path of the waiting.js inside the @mafalda/fsset package.

Doesn't Appear to work with Top level node Exports

Hello!

Thanks for the great package! However, I ran into an issue with packages that use a exports for the "top-level" node modules export. This package only appears to work if the import request is for a submodule like import x from "my-node-package/submodule";. it is possible for a package to use the exports field for root like import x from "my-node-package";.

For an example of this, see solid js which uses exports quite extensively to support different code paths in the server vs the browser.

https://github.com/solidjs/solid/blob/main/packages/solid/package.json#L37

In other words, jest-node-exports-resolver seems to work correctly when importing solid-js/web but not solid-js. i was able to work around this by making two changes to the resolver:

    if (!request.startsWith("@")) {
      if (length > 1) {
        packageName = pkgPathParts[0];
        submoduleName = `./${pkgPathParts.slice(1).join("/")}`;
      } else { // <- added this else
        packageName = request;
        submoduleName = ".";
      }
    } else if (length > 2) {
      packageName = pkgPathParts.slice(0, 2).join("/");
      submoduleName = `./${pkgPathParts.slice(2).join("/")}`; // <- I'm not sure if this line works for @namepspace/root packages but i didn't have any packages lie that to test
    } 

i also needed to add a check on conditions since this change alone broke for the package expect (which has a conditions of undefined) as far as i can tell, this is a good change regardless since we can skip the resolveExport function in more cases

        if (typeof exportValue === "string")
          targetFilePath = exportKey.endsWith("*")
            ? exportValue.replace(/\*/, submoduleName.slice(exportKey.length - 1))
            : exportValue;
        else if (conditions && exportValue !== null && typeof exportValue === "object") { // <- Modified this line
          function resolveExport(exportValue, prevKeys) {

I have no idea if these changes are good in general. i'd be happy to make a PR if you think this is good idea.

Doesn't work for older versions of Jest

Ahoy, it looks like this change makes conditions a requirement, but that stops it working for older versions of Jest that don't provide it. Could we provide a default set of conditions where Jest doesn't pass any to at least try to do the right thing?

Don't work with `exports` as string

When exports field is an string instead of an object, this module doesn't work. Just by replacing by hand exports for main it works and I can import the package, so probably it's an easy fix at

const hasExports = packageJson && packageJson.exports;
const isEntryPointsExports =
hasExports &&
Object.keys(packageJson.exports).every((k) => k.startsWith("."));
if (hasExports && isEntryPointsExports) {

"setupFiles" and "setupFilesAfterEnv" Jest options do not work properly when using jest-node-exports-resolver

In my jest.config.js I have a section using setupFiles and setupFilesAfterEnv, as follows:

setupFiles: [
path.resolve(__dirname, './tests/setup.js'),
'jest-localstorage-mock',
'jest-canvas-mock',
],

setupFilesAfterEnv: [path.resolve(__dirname, './tests/setupAfterEnv.js')],

On those files I have some additional Jest setup configuration.
However, if adding the exports resolver as explained on this GitHub documentation, eg:

resolver: 'jest-node-exports-resolver'

When running any Unit Test, I always get the following error:

Validation Error:
Module /plugin-manager/tests/setup.js in the setupFiles option was not found.
<rootDir> is: /plugin-manager

Not sure what's going on, but it seems the resolver is also trying to find "modules" on my test setup files ??

Content of setup.js:

import { configure } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
configure({ adapter: new Adapter(), disableLifecycleMethods: true });

Content of setupAfterEnv.js:

import '@testing-library/jest-dom/extend-expect';
import "jest-location-mock";

Is this a bug, or am I missing something ? Using Jest version 27.5.1

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.