Unexpected token import error in while running jest tests - javascript

I know this has been asked countless times, but I am not able to fix the problem inspite of following all the SO solutions and suggestions.
I came to know about jest a few days ago and tried to have my hands on it. There is a good tutorial mentioned on DZone about using jest to test react components. However, when I try testing one of the components from the starter directory, I am having this issue,
SyntaxError: Unexpected token import
at ScriptTransformer._transformAndBuildScript (../../../../../../usr/local/lib/node_modules/jest/node_modules/jest-runtime/build/ScriptTransformer.js:289:17)
at emitTwo (events.js:106:13)
As per suggested in this SO post, I have already installed babel-preset-react and added it to my webpack.config.js file.
Here is my webpack.config.js file, my package.json file , the .babelrc file
Please note that I have already gone through the solutions posted in these SO posts -
Link 1
Link 2
Link 3
which might be apparent from the changes in my .babelrc and webpack files
But I'm not able to fix the issue that I'm having. Please let me know if I am missing something here, since I have spent a good 3-4 hrs searching SO and other forums for any answer and I can't seem to find it.
Update 1: Here is my test file - Clock.test.jsx
import React from 'react';
import ReactDOM from 'react-dom';
import Clock from 'Clock';
describe('Clock',()=>{
it("renders without crashing",()=>{
const div = document.createElement('div');
ReactDOM.render(<Clock/>,div);
});
});

I was trying to follow up that tutorial but could not even install it without errors. As I see it, the tutorial is old, webpack 1 is deprecated, and other packages also undergone changes. You could try my steps, but it may not work for you.
In the starter/CountdownTimer folder run npm install. If it throws
this errors: “Cannot read property 'find' of undefined”, then run npm cache verify and npm install.
Then run npm install –save-dev jest#18.0.0 to install jest.
In the app folder create __tests__ folder in there create app.test.jsx
and Clock.test.jsx.
Add “jest” to the package.json test script.
Change your .babelrc.
Here is how the files look like:
// app.test.jsx
describe('App', () => {
it('should be able to run tests', () => {
expect(1 + 2).toEqual(3);
});
});
// Clock.test.jsx
import React from 'react';
import ReactDOM from 'react-dom';
// Note the path.
import Clock from '../components/Clock';
describe('Clock',()=>{
it("renders without crashing",()=>{
const div = document.createElement('div');
ReactDOM.render(<Clock/>,div);
});
});
// package.json
{
"name": "countdown-timer",
"version": "0.0.1",
"description": "",
"main": "server.js",
"scripts": {
"start": "node server.js",
"test": "jest"
},
"author": "Joyce Echessa",
"license": "MIT",
"dependencies": {
"express": "^4.14.0",
"react": "^15.4.0",
"react-dom": "^15.4.0"
},
"devDependencies": {
"babel-core": "^6.18.2",
"babel-loader": "^6.2.8",
"babel-preset-es2015": "^6.18.0",
"babel-preset-react": "^6.16.0",
"css-loader": "^0.26.0",
"foundation-sites": "^6.2.4",
"jest": "^18.0.0",
"jquery": "^3.1.1",
"node-sass": "^3.13.0",
"sass-loader": "^4.0.2",
"script-loader": "^0.7.0",
"style-loader": "^0.13.1",
"webpack": "^1.13.3"
}
}
// .babelrc
{
"presets": [["es2015"], ["react"]]
}
Run npm test. This worked for me to get tests passing, hope it will help you too.

Related

How can I use emotion with react-native-web?

I develop a cross-platform react-native application inside a monorepo and want to render my app using react-native-web in the browser. To achieve that I followed this guide https://mmazzarolo.com/blog/2021-09-22-running-react-native-everywhere-web/. I'm also using the metro-react-native-babel-preset package for compiling my web-app, as described in the react-native-web guide https://necolas.github.io/react-native-web/docs/multi-platform/. Here is a part of my craco.config.js file (I use create-react-app with craco):
// craco.config.js
const webpack = require("webpack");
const { getWebpackTools } = require("react-native-monorepo-tools");
const monorepoWebpackTools = getWebpackTools();
module.exports = {
babel: {
presets: ["module:metro-react-native-babel-preset", "#babel/preset-react"]
},
webpack: {
configure: (webpackConfig) => {
// Allow importing from external workspaces.
monorepoWebpackTools.enableWorkspacesResolution(webpackConfig);
// Ensure nohoisted libraries are resolved from this workspace.
monorepoWebpackTools.addNohoistAliases(webpackConfig);
return webpackConfig;
},
Now it seems like the metro-react-native-babel-preset preset is not compatible with the stylis library (imported by #emotion/react), because I get this error when launching the app in the browser (it compiles without errors):
Uncaught TypeError: (0 , _stylis.middleware) is not a function
at createCache (emotion-cache.browser.esm.js:288)
at Object.../node_modules/#emotion/react/dist/emotion-element-699e6908.browser.esm.js (emotion-element-699e6908.browser.esm.js:11)
at __webpack_require__ (bootstrap:851)
at fn (bootstrap:150)
at Object.<anonymous> (emotion-react.browser.esm.js:3)
at Object.../node_modules/#emotion/react/dist/emotion-react.browser.esm.js (emotion-react.browser.esm.js:347)
at __webpack_require__ (bootstrap:851)
at fn (bootstrap:150)
at Object.../node_modules...
I guess that the stylis-package cannot be imported correctly due to the metro-react-native-babel-preset preset, since without the preset the error is gone (but the compilation-step throws errors, so removing the preset is not a solution).
What do I have to change in my babel- / webpack-config or code to remove this error?
Minimum, reproducible example
https://github.com/Tracer1337/stackoverflow-mre
I think it is a problem with packages version.
When I try it, I also have this error.
But when updated packages to newer version it was gone (other error occured thought, but related to reactDOM).
I have updated react-scripts to 5.0.0;
See if it helps you as well.
{
"name": "#meme-bros/web",
...
"dependencies": {
"#emotion/react": "^11.7.1",
"#emotion/styled": "^11.6.0",
"#mui/material": "^5.2.3",
"#types/react": "^17.0.0",
"#types/react-dom": "^17.0.0",
"metro-react-native-babel-preset": "^0.66.2",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-native-web": "^0.17.5",
"react-scripts": "5.0.0",
"typescript": "^4.1.2"
},
"devDependencies": {
"#craco/craco": "^6.4.3",
"react-native-monorepo-tools": "^1.1.4"
},
...
Would you mind to follow these guidelines to run React Native app on web. Official Doc
And Add #emotion/react in compileNodeModules list

Babel-loader not transpiling JSX component. ModuleParseError

I'm trying to build a standalone component as a package. I'm using webpack to transpile all the CSS and JS/JSX files into JS. I'm able to build the package and pack it into a .tgz file using npm pack. However, when I install the package in another project and try using the component from the installed package. I'm getting this error:
ModuleParseError: Module parse failed: Unexpected token (34:8)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file.
And, in the terminal of the running project, I get this:
error - SyntaxError: Cannot use import statement outside a module
webpack.config.js
const path = require('path')
module.exports = {
mode:'production',
entry:'./src/components/StandaloneComponent.js',
output:{
path:path.join(__dirname,'dist'),
filename:'StandaloneComponent.js',
libraryTarget:"commonjs2"
},
module:{
rules:[
{
test:/\.js|jsx$/,
exclude:/(node_modules)/,
use:'babel-loader'
},
{
test:/\.css$/,
use:[
'style-loader',
'css-loader'
]
}
]
},
resolve:{
alias:{
'react':path.resolve(__dirname,'./node_modules/react'),
'react-dom':path.resolve(__dirname,'./node_modules/react-dom'),
'next':path.resolve(__dirname,'./node_modules/next')
}
},
externals:{
react:{
commonjs:"react",
commonjs2:"react",
amd:"React",
root:"React"
},
"react-dom":{
commonjs:"react-dom",
commonjs2:"react-dom",
amd:"ReactDOM",
root:"ReactDOM"
},
next:{
commonjs:"next",
commonjs2:"next",
amd:"Next",
root:"Next"
}
}
}
package.json
{
"name": "testcomponent",
"version": "1.0.3",
"description": "A lightweight and easy to use package.",
"main": "./src/components/StandaloneComponent.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "webpack"
},
"keywords": [
"NextJS",
"react"
],
"peerDependencies": {
"next": "^12.0.7",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"prop-types": "^15.7.2"
},
"devDependencies": {
"#babel/core": "^7.16.0",
"#babel/preset-env": "^7.16.4",
"#babel/preset-react": "^7.16.0",
"#babel/preset-stage-0": "^7.8.3",
"babel-loader": "^8.2.3",
"css-loader": "^6.5.1",
"next": "^12.0.7",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"style-loader": "^3.3.1",
"webpack": "^5.64.4",
"webpack-cli": "^4.9.1"
}
}
.babelrc
{
"presets": [
"#babel/preset-env",
"#babel/preset-react"
]
}
I further installed this package in another project like this:
npm install path/to/tgz/testcomponent-1.0.3.tgz
And then imported the component as:
import StandaloneComponent from 'testcomponent'
As a possible workaround, I tried changing the extension of the component file from .js to .jsx and rebuilt the .tgz, but got the same result.
Looking at the error, I feel that babel-loader is unable to convert JSX into JS, which further is causing the import error, but I'm not entirely sure about it.
What could be causing this error?
Any help is appreciated.
Thanks.
The regex rule that you are using to load the JS and JSX file i.e. test:/\.js|jsx$/ seems incorrect in this case. You can fix it in following two ways:
Using capture groups: So when using or you need to capture the both the character sets as /\.(js|jsx)$/. This will consider both js and jsx extension. The earlier version just doesnt match the regex properly because of missing character set.
Using ? occurrence: You can also modify your regex to use the x as an zero or one occurrence using ? matcher. So the other option will be /\.jsx?$/
I believe you need to include the package you installed under include otherwise it looks like Webpack is configured to ignore your node_modules folder:
exclude: /(node_modules)/,
So make sure to let Webpack know what folders in node_modules that you do want to compile
include: [
path.resolve(__dirname, 'node_modules/testcomponent'
]

Jest and Create-react-app: Cannot use import statement outside a module

I have a React Native application where I have some files with some methods that calls certain endpoints. When I try to run Jest is throwing me an error at a local file that is imported.
I have the next package.json:
{
"name": "appName",
"version": "1.0.0",
"description": "some description",
"main": "index.js",
"scripts": {
"test": "jest"
},
"author": "",
"license": "ISC",
"dependencies": {},
"devDependencies": {
"#babel/core": "^7.14.2",
"#react-native-community/async-storage": "^1.12.1",
"#react-native-community/netinfo": "^6.0.0",
"isomorphic-fetch": "^3.0.0",
"jest": "^26.6.3",
"jest-fetch-mock": "^3.0.3"
},
"jest": {
"automock": false,
"setupFiles": [
"./jest.setup.js"
]
}
}
And the jest.setup.js file is the following:
import mockRNCNetInfo from '#react-native-community/netinfo/jest/netinfo-mock.js'
jest.mock('#react-native-community/netinfo', () => mockRNCNetInfo)
For the moment, this content is commented, otherwise will throw the same error like in the picture.
I tried to test the same stuff in another project where this #react-native-community/netinfo package wasn't saved in devDependencies but in dependencies and it worked but I am not sure if this is the problem. In this specific project I can't let this package as a dependency, it should be in devDependencies.
I found a lot of issues on this but none of them worked on this case, I don't know what to do anymore. Thank you for your time!
I got this error when I was creating tests with Create-react-app Typescript Jest Axios. Perhaps the following entry in package.json might help.
"jest": {
"transform": {
"^.+\\.[t|j]sx?$": "babel-jest"
},
{ "transformIgnorePatterns": [
"node_modules/(?!#shotgunjed)/"
]
},
I found this answer on internet and it worked for me with some small add-ons but I will post it here maybe will help someone in future:
install babel-jest, babel-preset-env, #babel/runtime and react (the last one might be possible to be necessary only if some other package requires it)
create .babelrc file in root directory and add:
{
"env": {
"test": {
"plugins": ["transform-es2015-modules-commonjs"]
}
}
}
Run your code and should be good to go

Creating a Kotlin React Wrapper around Paypal Downshift

I've been trying without success to create a Kotlin JS wrapper around the PayPal Downshift library. I can get Downshift to work fine outside the Kotlin ecosystem, but am having no luck when trying to integrate it into a Kotlin JS application.
I've stripped all the properties out to the following:-
#file:JsModule("downshift")
package components.downshift
import react.Component
import react.RProps
import react.RState
import react.ReactElement
#JsName("Downshift")
external class DownshiftComponent : Component<RProps, RState> {
override fun render(): ReactElement?
}
Then inside my React app's render method I add the following:-
child<RProps, DownshiftComponent> { }
The equivalent in JSX works inside a custom component (although renders nothing!)
render() {
return (
<Downshift/>
)
}
The error I end up with is as follows:-
TypeError: Cannot read property '$metadata$' of undefined
getOrCreateKClass
node_modules/kotlin/kotlin.js:27368
27365 | if (jClass === String) {
27366 | return PrimitiveClasses_getInstance().stringClass;
27367 | }
> 27368 | var metadata = jClass.$metadata$;
| ^ 27369 | if (metadata != null) {
27370 | if (metadata.$kClass$ == null) {
27371 | var kClass = new SimpleKClassImpl(jClass);
To me this is suggesting the class from the "downshift" package can't be found (hence undefined). If that is the case what is the correct way to import Downshift so Kotlin can use it?
I have installed the downshift module using npm
npm install downsift --save
and it is showing in my package.json file:-
{
"name": "pop-up-shop-ui",
"version": "0.1.0",
"private": true,
"dependencies": {
"#material-ui/core": "^3.8.2",
"#material-ui/icons": "^3.0.2",
"#material-ui/lab": "^3.0.0-alpha.28",
"d3-shape": "^1.2.2",
"downshift": "^3.2.0",
"prop-types": "latest",
"react": "^16.7.0",
"react-autosuggest": "^9.4.3",
"react-currency-format": "^1.0.0",
"react-dom": "^16.7.0",
"react-google-charts": "^3.0.10",
"react-router": "^4.3.1",
"react-router-dom": "^4.3.1",
"react-scripts": "2.1.3"
},
"devDependencies": {
"react-scripts-kotlin": "3.0.3"
},
"scripts": {
"start": "react-scripts-kotlin start",
"build": "react-scripts-kotlin build",
"eject": "react-scripts-kotlin eject",
"gen-idea-libs": "react-scripts-kotlin gen-idea-libs",
"get-types": "react-scripts-kotlin get-types --dest=src/types",
"postinstall": "npm run gen-idea-libs"
}
}
Here is the standard import when using a react/jsx component
import Downshift from "downshift";
Which matches the #file:JsModule("downshift") and #JsName("Downshift") annotations.
Any help getting this working would be appreciated
I've encountered this problem few days ago. The error is very confusing, but after some digging I found that the problem originates in the type (in your case Downshift) being undefined. You can easily catch it by writing something like prinltn(DownshiftComponent::class) before initializing react.
The problem is probably with the build. Don't forget to add the npm dependency in it. Also sometimes incremental build glitches and you need to do a clean build to see changes.

Error in node_modules/react-native/Libraries/Modal/Modal.js while testing with Jest

I'm making a simple snapshot test with Jest and just get this error:
home.test.js
import React from 'react';
import Home from './index';
import renderer from 'react-test-renderer';
it('renders home', ()=> {
const view = renderer.create(
<Home></Home>
).toJSON();
expect(view).toMatchSnapshot();
});
Unfortunately I don't have idea what is the problem here. I thought the test is well written.
Any help would be great.
HOW I SOLVED THE ERROR KEEPING MY TEST FROM RUNNING
Ran into this error, which kept my tests from running
Error Page
After many hours of frustration, in which I deleted the node_modules folder twice and reinstalled and scoured through Stackoverflow and Google without any solution, I decided to create a new CRNA project and see if it would have the same issues.
When I saw the issues didn’t exist in the new repo, I used the following steps to get it to work:
Delete the node_modules folder again
Upgraded my package.json file, with the key changes shown below:
```
{
"devDependencies": {
"react-native-scripts": "1.5.0",
"jest-expo": "^21.0.2",
"react-test-renderer": "16.0.0-alpha.12"
},
"jest": {
"preset": "jest-expo",
"transformIgnorePatterns": [
"node_modules/(?!react-native|expo|react-navigation|native-base-shoutem-theme|#shoutem/theme|#shoutem/animation|#shoutem/ui|tcomb-form-native)"
]
},
"dependencies": {
"react-native": “0.48.4”,
"expo": "^21.0.2",
"react": "16.0.0-alpha.12"
},
3. The core difference was in upgrading react-native from 0.48.0 to 0.48.4; react-native-scripts from 1.2.1 to 1.5.0 and including the transformIgnorePatterns under the jest option.
NOTE: The portion from *native-base* in the transformIgnorePatterns was included because I used NativeBase in the project.
4. I then added a .babelrc with the following details:
{
"presets": ["babel-preset-expo"],
"env": {
"development": {
"plugins": ["transform-react-jsx-source"]
}
}
}
```
5. Running the tests now give me the result:
Passing Tests
All tests are green

Categories