k-g-a / jest-node-exports-resolver Goto Github PK
View Code? Open in Web Editor NEWLicense: MIT License
License: MIT License
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.
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';
| ^
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
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;
}
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.
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.
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?
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
jest-node-exports-resolver/index.js
Lines 82 to 87 in 276a492
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
Cannot find module '@jest/expect' from 'node_modules/jest-circus/build/legacy-code-todo-rewrite/jestAdapterInit.js'
Was trying to follow some walk around solution(testing-library/jest-dom#457 (comment)), and it fixes the error by removing the jest-node-exports-resolver
Still feel like it needs to be fixed properly.
At
jest-node-exports-resolver/index.js
Line 25 in 3546970
package.json
file is required, that means it needs to be added to the exports
field. Use it instead require.resolve()
of the package itself, append package.json
to the path, and require the file directly by hand to parse it.A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.