Jest - Next.js - Unexpected token error inside jest node-modules - javascript

I installed jest with the following command on my next js project
npm i --save-dev jest #testing-library/react #testing-library/jest-dom jest-environment-jsdom
then added jest.config.json file with the below code
const nextJest = require("next/jest");
const createJestConfig = nextJest({
dir: "./",
});
const customJestConfig = {
moduleDirectories: ["node_modules", "<rootDir>/"],
testEnvironment: "jest-environment-jsdom",
};
module.exports = createJestConfig(customJestConfig);
Now, when I run 'npm test', I get the following error
Test suite failed to run
D:\my-project\node_modules\#jest\reporters\build\GitHubActionsReporter.js:67
#getMessageDetails(failureMessage, config) {
^
SyntaxError: Unexpected token '('
at Object. (node_modules/#jest/reporters/build/index.js:75:3)
I've tried a lot of solutions, updating the config file, adding babel plugins, none worked. And I haven't found any mention of this error online. What is the issue here?
My dev-dependencies versions -
"devDependencies": {
"#testing-library/jest-dom": "^5.16.5",
"#testing-library/react": "^13.4.0",
"eslint": "8.14.0",
"eslint-config-next": "12.1.5",
"jest": "^29.0.3",
"jest-environment-jsdom": "^29.0.3"
}

As mentioned by jonrsharpe, the fix is to make sure you have an updated version of node installed.
This issue isn't limited to using Jest with a Next.js solution, but also applies to Jest being used with React/VanillaJs/etc

Related

Cannot run Jest (27.4.6) tests: defaultResolver is not defined by export

After upgrading Angular version of my app to 12, I decided to upgrade other libraries like jest as well:
"jest": "^27.4.6", (from 24.1.0)
"jest-canvas-mock": "^2.2.0",
"jest-junit": "^13.0.0", (from ^9.0.0)
"jest-preset-angular": "11.0.1",
"jest-resolve": "^27.4.6", (added this one)
"ts-jest": "27.1.2" (from 24.0.0)
This is how my jest.config.js looks like:
const jestPresetAngularSerializers = require('jest-preset-angular/build/serializers');
module.exports = {
name: 'sam-web',
preset: '../../jest.config.js',
coverageDirectory: '../../coverage/apps/sam-web',
reporters: [
'default',
[
'jest-junit',
{
outputDirectory: 'reports',
outputName: 'junit-sam-web.xml',
},
],
],
snapshotSerializers: [jestPresetAngularSerializers, 'jest-preset-angular/build/serializers/html-comment'],
transformIgnorePatterns: ['/node_modules/(?!lodash-es).+\\.js$'],
collectCoverageFrom: ['src/app/**/*.ts', '!src/app/**/*.module.ts'],
cacheDirectory: '../../.jest-cache',
};
I'm also using import 'jest-preset-angular/setup-jest'; instead of import 'jest-preset-angular';
This is my app things and their versions:
Angular CLI: 12.2.14
Node: 14.15.0
Package Manager: yarn 1.22.17
OS: win32 x64
Package Version
------------------------------------------------------------
#angular-devkit/architect 0.801.1
#angular-devkit/build-angular 12.2.14
#angular-devkit/core 8.1.1
#angular-devkit/schematics 8.1.1
#angular/cdk 12.2.13
#angular/cli 12.2.14
#angular/material 12.2.13
#angular/material-moment-adapter 12.2.13
#schematics/angular 12.2.14
rxjs 7.4.0
typescript 4.3.5
And this is the error what I get when I'm trying to run the tests:
An unhandled exception occurred: Package subpath './build/defaultResolver' is not defined by "exports" in C:\Users\Dominik\Desktop\Work\web_gui\node_modules\jest-resolve\package.json
See "C:\Users\Dominik\AppData\Local\Temp\ng-9Gl1h1\angular-errors.log" for further details.
error Command failed with exit code 127.
I have tried to remove node_module and yarn.lock, clean cache, install everything one more time but every time is the same. I found a similar issue on some page where the solution was to run npm update but similar command for yarn doesn't help me. Maybe someone of you can help me?

Configure jest with latest version of d3-path

For some reason, my jest configuration doesn't work with the latest version of d3-path#3.0.1. It worked fine with version 2.0.0. I guess it has something to do with d3-path switching to ESM, but I was already using ES6 in my own code, so I don't get why it suddenly doesn't work anymore. I have the following packages installed:
"dependencies": {
"d3-path": "^3.0.1"
},
"devDependencies": {
"#babel/core": "^7.15.8",
"#babel/preset-env": "^7.15.8",
"babel-jest": "^27.3.1",
"jest": "^27.3.1"
}
My babel.config.js:
module.exports = {
presets: [['#babel/preset-env', {targets: {node: 'current'}}]],
};
My index.js:
import { path } from 'd3-path'
export default () => path()
The test file:
import fn from '../src/index.js'
describe('test', () => {
it('works', () => {
fn()
expect(2 + 2).toBe(4)
})
})
The error message:
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){export {default as path} from "./path.js";
^^^^^^
SyntaxError: Unexpected token 'export'
> 1 | import { path } from 'd3-path'
To reproduce:
git clone https://github.com/luucvanderzee/jest-problem.git
cd jest-problem
npm i
npm run test
// The test runs without failure- this is because we're currently still using d3-path#2.0.0
npm uninstall d3-path && npm install d3-path // (upgrade to d3-path#3.0.1)
npm run test
// Now the test fails.
How should I configure jest and/or babel to solve this issue?
EDIT:
I already tried the following (from this page of the jest docs):
Creating a jest.config.js file with the following:
module.exports = {
transform: {}
}
Changing my "test" command from "jest" to "node --experimental-vm-modules node_modules/jest/bin/jest.js"
This gives me another error:
/home/luuc/Projects/javascript/jest-problem/test/test.test.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){import fn from '../src/index.js'
^^^^^^
SyntaxError: Cannot use import statement outside a module
I also don't get what is meant by
• To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
Isn't the problem that the module is not transformed? Would adding an ignore pattern not just lead to the module not getting transformed?
Problem
The error happens because jest does not send the content of node_modules to be transformed by babel by default.
The following output line of npm run test indicates one way to solve the problem:
• To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
Solution
The configuration of jest should be updated in order to instruct it to transform the ESM code present in d3-path dependency.
To do so, add the following to a jest.config.js file in the root directory of the project:
module.exports = {
transformIgnorePatterns: ['node_modules/(?!(d3-path)/)']
}
npm run test runs fine after that.
The transformIgnorePatterns option is documented here.
Edit - including more modules
In order to include all modules starting with d3, the following syntax may be used:
transformIgnorePatterns: ['/node_modules/(?!(d3.*)/)']
TLDR;
transformIgnorePatterns: [
"/node_modules/(?!d3|d3-array|d3-axis|d3-brush|d3-chord|d3-color|d3-contour|d3-delaunay|d3-dispatch|d3-drag|d3-dsv|d3-ease|d3-fetch|d3-force|d3-format|d3-geo|d3-hierarchy|d3-interpolate|d3-path|d3-polygon|d3-quadtree|d3-random|d3-scale|d3-scale-chromatic|d3-selection|d3-shape|d3-time|d3-time-format|d3-timer|d3-transition|d3-zoom}|internmap|d3-delaunay|delaunator|robust-predicates)"
]
For the ones reaching this page after updating recharts dependency, here I found the solution, provided by them.

Trying ES6 style import gives 'Cannot use import statement outside a module'

I am trying to write a javascript test in intellij for which I need to import some dependancies and I want to use ES6 style import statements but getting error
/usr/local/bin/node /workspace/rr-sample/node_modules/mocha/bin/_mocha
--ui bdd --reporter "/Users/me/Library/Application Support/IntelliJIdea2019.1/NodeJS/js/mocha-intellij/lib/mochaIntellijReporter.js"
tests/*.test.js /workspace/rr-sample/tests/App.test.js:3
import chai from 'chai'
^^^^^^
SyntaxError: Cannot use import statement outside a module
at wrapSafe (internal/modules/cjs/loader.js:1043:16)
at Module._compile (internal/modules/cjs/loader.js:1091:27)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1160:10)
at Module.load (internal/modules/cjs/loader.js:976:32)
at Function.Module._load (internal/modules/cjs/loader.js:884:14)
at Module.require (internal/modules/cjs/loader.js:1016:19)
at require (internal/modules/cjs/helpers.js:69:18)
at /workspace/rr-sample/node_modules/mocha/lib/mocha.js:334:36
at Array.forEach (<anonymous>)
at Mocha.loadFiles (/workspace/rr-sample/node_modules/mocha/lib/mocha.js:331:14)
at Mocha.run (/workspace/rr-sample/node_modules/mocha/lib/mocha.js:809:10)
at Object.exports.singleRun (/workspace/rr-sample/node_modules/mocha/lib/cli/run-helpers.js:108:16)
at exports.runMocha (/workspace/rr-sample/node_modules/mocha/lib/cli/run-helpers.js:142:13)
at Object.exports.handler (/workspace/rr-sample/node_modules/mocha/lib/cli/run.js:292:3)
at Object.runCommand (/workspace/rr-sample/node_modules/yargs/lib/command.js:242:26)
at Object.parseArgs [as _parseArgs] (/workspace/rr-sample/node_modules/yargs/yargs.js:1087:28)
at Object.parse (/workspace/rr-sample/node_modules/yargs/yargs.js:566:25)
at Object.exports.main (/workspace/rr-sample/node_modules/mocha/lib/cli/cli.js:68:6)
at Object.<anonymous> (/workspace/rr-sample/node_modules/mocha/bin/_mocha:10:23)
at Module._compile (internal/modules/cjs/loader.js:1121:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1160:10)
at Module.load (internal/modules/cjs/loader.js:976:32)
at Function.Module._load (internal/modules/cjs/loader.js:884:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:67:12)
at internal/main/run_main_module.js:17:47
What exactly is the issue? I found this link (and others) http://xahlee.info/js/js_import_export.html which tells you how to fix this error but in another context which doesn't help me, and it doesn't explain what the problem is.
In case it is helpful here is the code I am using.
//const chai = require("chai");
import chai from 'chai'
const React = require("react");
const expect = chai.expect;
describe('how it works first-time test', () => {
it('checks equality', () => {
const val = false;
expect(val).to.be.false;
});
});
The easiest way to run Mocha tests written in ES6 is compiling them on-the-fly using Mocha --require #babel/register option (see https://github.com/mochajs/mocha/wiki/compilers-deprecation#what-should-i-use-instead-then). Of course, you need to make sure to install the corresponding modules and set up the .babelrc accordingly
package.json:
"dependencies": {
"#babel/cli": "^7.7.4",
"#babel/core": "^7.7.4",
"#babel/preset-env": "^7.7.4",
"#babel/register": "^7.7.4",
...
}
.babelrc:
{
"presets": [
[
"#babel/preset-env"
]
]
}
See also https://dev.to/bnorbertjs/my-nodejs-setup-mocha--chai-babel7-es6-43ei
I had the same problem when updating one of my ts libraries to es6 modules instead of commonjs. After the change in the tsconfig.json my npm run test produced the mentioned error.
import chai from 'chai'
^^^^^^
SyntaxError: Cannot use import statement outside a module
I solved it without babel by adding an own tsconfig file just for testing.
tsconfig.testing.json
{
"compilerOptions": {
"module": "commonjs",
"target": "es6"
},
"include": ["**/*.spec.ts"]
}
To run the tests via script in package.json
"test": "cross-env TS_NODE_PROJECT=\"tsconfig.testing.json\" mocha -r ts-node/register src/**/*.spec.ts",
(cross-env to set the env variable os independent)
I was able to get this working by adding a .mocharc.yaml file at the source of my project with the following:
require: '#babel/register'
source: https://github.com/mochajs/mocha-examples/tree/master/packages/babel
For me, I was not able to run it via inline debug option in intellj. So I set extra mocha option and this solved the issue.
--compilers js:babel-core/register
Also, to run via terminal
npx mocha --compilers js:babel-core/register
The cause of my issue was - an old version of Mocha, in fact any <6.0.0, even when the 'require: #babel/register' was configured. I updated Mocha to 9.0.0, I also updated Babel libraries to the latest and the problem was solved.
As it is also suggested in the Mocha docs, use config file, like '.mocharc.js', where you have to declare required Babel dependancy like in this example:
.mocharc.js
module.exports = {
...
require: '#babel/register',
...
}
package.json
{
...
"devDependencies": {
"#babel/core": "^7.9.0",
"#babel/preset-env": "^7.3.4",
"#babel/preset-react": "7.18.6",
"#babel/register": "^7.9.0"
...
"mocha": "^9.0.0",
}
}
According to the doc:
https://nodejs.org/api/esm.html#esm_code_import_code_statements
So you have to ensure execute the script as an es module.
e.g. Execute the script using babel-node instead of Nodejs to enable the es6 or newer.

How to configure babel correctly to use lodash-es?

I need to use lodash-es in my project, but I can't configure my babel correctly, it always reports errors like SyntaxError: Unexpected identifier
hello.js
import upperCase from 'lodash-es/upperCase'
console.log(upperCase('lodash-es'));
package.json
{
"scripts": {
"demo": "babel-node hello"
},
"devDependencies": {
"#babel/cli": "^7.0.0",
"#babel/core": "^7.0.0",
"#babel/node": "^7.0.0",
"#babel/preset-env": "^7.0.0"
},
"dependencies": {
"lodash-es": "4.17.11"
}
}
.babelrc
{
"presets": [
"#babel/preset-env"
]
}
When run babel-node hello, it reports error like:
> /javascript-babel-node-use-lodash-es-issue-demo
> babel-node hello
/Users/freewind/workspace/javascript-babel-node-use-lodash-es-issue-demo/node_modules/lodash-es/upperCase.js:1
(function (exports, require, module, __filename, __dirname) { import createCompounder from './_createCompounder.js';
^^^^^^^^^^^^^^^^
SyntaxError: Unexpected identifier
at new Script (vm.js:79:7)
at createScript (vm.js:251:10)
at Object.runInThisContext (vm.js:303:10)
I've also setup a small demo for this issue, you can clone and try it if you need: https://github.com/freewind-demos/javascript-babel-node-use-lodash-es-issue-demo
Adapted from https://stackoverflow.com/a/31822668/3563013
require("#babel/register")({
ignore: [/node_modules\/(?!lodash-es)/],
});
babel-node by default ignores the node_modules directory. Which is a good thing, else it would be unnecessarily heavy. Packages in node_modules are (at the moment) expected to be in commonjs format. Instead of using lodash-es (es6 format) you should just use lodash (commonjs format). It has exactly the same functionality, the only difference is the format it is written in. More information about that here.
So either tweak babel-node to unignore node-modules/lodash-es (not recommended!) or just install lodash with npm install --save lodash and then rewrite your import like:
import upperCase from 'lodash/upperCase' // instead of lodash-es
console.log(upperCase('lodash-es'));

Meteor + LitElement (Polymer 3) issue with importing

I had an issue with importing the LitElement module into a Meteor project:
I'm starting a new test project with Meteor 1.7+ and am using LitElement for a few components.
I installed Meteor like so:
meteor create meteor-lithtml --release 1.7.1-beta.29 --bare
I installed like so:
meteor npm install --save #polymer/lit-element
My node_modules directory looks like so:
My package.json file:
{
"name": "myapp",
"private": true,
"scripts": {
"start": "meteor run"
},
"dependencies": {
"#babel/runtime": "^7.0.0-beta.56",
"#polymer/lit-element": "^0.5.2",
"#vaadin/router": "^1.0.0",
"meteor-node-stubs": "^0.4.1",
"redux": "^4.0.0"
},
"meteor": {
"mainModule": {
"client": "client/index.js",
"server": "server/index.js"
}
}
}
The typical way I see lit-element imported is not working...
Just adding an index.js file and importing the lit-element module generates errors. If I remove the import from the index.js file, the errors go away.
\\ client\index.js
import { LitElement, html } from '#polymer/lit-element';
The very first error:
Uncaught SyntaxError: Unexpected token {
modules.js?hash=182125a3fa97eaa24f6d313584ca593c3aed2103:984
Points to this location:
Expanding node_modules to look into this file:
Why am I getting the unexpected { token?
NOTE: I'm asking this question here just in case a Meteor user stumbles by with the same issue and needs help.
Just in case we have any more Meteor users stop by with an issue like this, here are the references to the explanation & solution:
explanation: https://forums.meteor.com/t/litelement-import-litelement-html/45042/8?u=aadams
solution: https://github.com/aadamsx/meteor-lithtml/pull/1

Categories

Resources