Jest encountered an unexpected token React - javascript

This is screenshot of error:
I have 2 tests, the first one is working alright: sum.js :
function sum(a, b) {
return a + b;
}
module.exports = sum;
sum.test.js
const sum = require('./sum');
test('adds 2 + 5 to equal 7', () => {
expect(sum(2, 5)).toBe(7);
});
it works okay, prints message in console.
the second one (I dont sure) is set by default by create-react-app
App.test.js :
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
it('renders without crashing', () => {
const div = document.createElement('div');
ReactDOM.render(<App />, div);
ReactDOM.unmountComponentAtNode(div);
});
App.js :
import React, { Component } from 'react';
import {HashRouter} from "react-router-dom";
import Routes from './routes';
import Alerts from './app/components/alerts';
import Navbar from '../src/app/navbar/navbar'
import Auth from './app/settings/auth';
import Register from './app/entities/user/modify-modal';
import './index.scss';
class App extends Component {
componentWillMount(){
}
render() {
return (
<HashRouter>
<>
<Auth></Auth>
<Navbar></Navbar>
<Alerts></Alerts>
<Register/>
<div className={"content-root"}>
<Routes/>
</div>
</>
</HashRouter>
);
}
}
export default App;
package.json
{
"name": "x5_r_app",
"version": "0.1.0",
"private": true,
"dependencies": {
"#babel/cli": "^7.2.3",
"#babel/plugin-proposal-class-properties": "^7.4.0",
"#babel/plugin-syntax-dynamic-import": "^7.2.0",
"#babel/preset-env": "^7.4.1",
"#babel/preset-flow": "^7.0.0",
"#babel/preset-react": "^7.0.0",
"#fortawesome/fontawesome-free": "^5.7.1",
"#fortawesome/fontawesome-svg-core": "^1.2.12",
"#fortawesome/free-solid-svg-icons": "^5.6.3",
"#fortawesome/react-fontawesome": "^0.1.3",
"axios": "^0.18.0",
"babel-eslint": "^10.0.1",
"babel-loader": "^8.0.5",
"bootstrap": "^4.2.1",
"jest": "^24.5.0",
"jest-cli": "^24.5.0",
"jsdom": "^14.0.0",
"moment": "^2.23.0",
"node-sass": "^4.11.0",
"react": "^16.7.0",
"react-addons-test-utils": "^15.6.2",
"react-bootstrap": "^1.0.0-beta.5",
"react-bootstrap-typeahead": "^3.2.4",
"react-datetime": "^2.16.3",
"react-debounce-input": "^3.2.0",
"react-dom": "^16.7.0",
"react-router-dom": "^4.3.1",
"react-scripts": "2.1.2",
"react-select": "^2.3.0",
"reactstrap": "^7.0.2",
"rxjs": "^6.3.3",
"scss": "^0.2.4",
"test": "^0.6.0"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "jest",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": [
">0.2%",
"not dead",
"not ie <= 11",
"not op_mini all"
],
"devDependencies": {
"#babel/core": "^7.4.0",
"babel-core": "^6.26.3",
"babel-jest": "^24.5.0"
}
}
package-lock.json is 20000 rows of code, so I dont know, what part of it is needed for explanation of my problem, all guides that I've read about this problem were useless for me, so I am asking here.

The issue is that the app was bootstrapped with create-react-app, but then the latest version of Jest was also installed and the npm test script within package.json was changed to launch jest directly.
The test failed since Jest was not configured to transpile the JSX syntax.
Tests that use syntax like JSX have to be transpiled before they can be run by Jest.
create-react-app includes react-scripts which handles all of that configuration automatically.
If an app is bootstrapped with create-react-app then Jest does not need to be installed and configured manually.
If an app is not bootstrapped with create-react-app, or if the app is ejected from create-react-app, then Jest needs to be installed and configured to transpile the test code.

Related

Error with #reduxjs/toolkit and Typescript - TS1005

After installing the required packages to run react-redux and #reduxjs//toolkit in my current projects, I ran into this error after running npm start:
TypeScript error in C:/Users/xxx/Documents/xxx/node_modules/#reduxjs/toolkit/dist/configureStore.d.ts(1,13):
'=' expected. TS1005
1 | import type { Reducer, ReducersMapObject, Middleware, Action, AnyAction, StoreEnhancer, Store, Dispatch, PreloadedState, CombinedState } from 'redux';
My store is this:
import { configureStore } from "#reduxjs/toolkit";
import securityReducer from "../features/security/securitySlice.js";
const store = configureStore({
reducer: {
security: securityReducer,
},
});
export default store;
My index.tsx file contains this:
import React, { useEffect, useState } from "react";
import ReactDOM from "react-dom";`
import "./index.css";`
import AppContainer from "./AppContainer.js";
import * as serviceWorker from "./serviceWorker";
import store from "./app/store.jsx";
import { Provider } from "react-redux";
ReactDOM.render(
<React.StrictMode>
<Provider store={store}>
<AppContainer />
</Provider>
</React.StrictMode>,
document.getElementById("root")
);
serviceWorker.unregister();
And my package.json file is this:
{
"name": "my-app",
"version": "0.1.0",
"dependencies": {
"#aws-amplify/ui-react": "^1.2.0",
"#material-ui/core": "^4.11.3",
"#material-ui/icons": "^4.11.2",
"#reduxjs/toolkit": "^1.6.1",
"#types/react-router-dom": "^5.1.7",
"amazon-cognito-identity-js": "^5.0.3",
"amazon-cognito-identity-js-typescript": "^1.22.0",
"aws-amplify": "^4.0.2",
"aws-sdk": "^2.799.0",
"axios": "^0.21.1",
"bootstrap": "^4.4.1",
"cors": "^2.8.5",
"lodash": "^4.17.15",
"material-ui-dropzone": "^3.5.0",
"moment": "^2.25.3",
"rc-slider": "~9.2.4",
"react": "^16.13.0",
"react-bootstrap": "^1.0.0-beta.17",
"react-bootstrap-icons": "^1.1.0",
"react-dom": "^16.13.0",
"react-google-charts": "^3.0.15",
"react-icons": "^4.2.0",
"react-redux": "^7.2.4",
"react-router-dom": "^5.2.0",
"react-scripts": "3.4.0",
"redux": "^4.1.0",
"redux-ts": "^4.3.0",
"typescript": "~3.8.2"
},
"scripts": {
"start": "react-scripts start",
"test:coverage": "react-scripts test --watchAll=false --coverage",
"build": "react-scripts build",
"test": "react-scripts test --watchAll=false",
"test:watch": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"devDependencies": {
"#testing-library/jest-dom": "^4.2.4",
"#testing-library/react": "^9.3.2",
"#testing-library/user-event": "^7.1.2",
"#types/enzyme": "^3.10.5",
"#types/jest": "^24.0.0",
"#types/lodash": "^4.14.149",
"#types/node": "^12.0.0",
"#types/rc-slider": "~8.6.5",
"#types/react": "^16.9.0",
"#types/react-dom": "^16.9.0",
"#types/react-redux": "^7.1.18",
"#types/redux": "^3.6.0",
"enzyme": "^3.11.0",
"enzyme-adapter-react-16": "^1.15.2",
"enzyme-to-json": "^3.4.4",
"node-sass": "^4.13.1"
}
}
I read from some posts that my version of typescript needed to be updated to 3.8 but it still doesn't seem to solve the issue.
Thank you so much if anyone knows how to fix this error.
Maybe you can upgrade your typescript version to "^4.1.2", I also have the same problem with you, and I fix that with this

Test failures during styles file imports

Encountering issues with setting up Jest for React without the use of Create-React-App.
I do not want to use CRA thus sticking with babel and webpack config setup which does work less Jest.
Jest itself is working fine for testing. It only fails when a component has a css/scss file import.
Seen many similar issues here and tried out the solutions but the issue persists.
Could I get some help with what am doing wrong pls? Thanks.
These are some of the solutions I have tried out which is not working for me.
Tried accepted solution and also the other 2 solutions for this:
jest unexpected token when importing css
A Medium Blog with similar solution
https://stackoverflow.com/questions/51994111/jest-encountered-an-unexpected-token
Plus a couple of other examples more related to Vue but similar solution.
The error output as follows:
Jest encountered an unexpected token
Details:
.some-class {
^
This is class being tested:
import React from 'react';
import '../styles/styles.scss' // line causing issue
const App = () => {
const env = process.env.NODE_ENV;
return (
<div>
<h1>sample header</h1>
<p>{`This is in ${env} environment`}</p>
</div>
);
};
export default App;
The Test class
import App from "../../components/App";
import React from "react";
import {shallow} from "enzyme";
it('should get a matching snapshot', () => {
const wrapper = shallow(<App/>)
expect(wrapper.find('h1').text()).toBe('sample header')
expect(wrapper).toMatchSnapshot()
});
Styles file: styles.scss
.some-class {
color: aliceblue;
}
package.json for reference:
{
"name": "tar",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "cross-env NODE_ENV=beta webpack-dev-server",
"build-prod": "cross-env NODE_ENV=production webpack -p",
"build-beta": "cross-env NODE_ENV=beta webpack",
"test": "jest --config=jest.config.json"
},
"author": "",
"license": "ISC",
"devDependencies": {
"#babel/core": "^7.11.6",
"#babel/preset-env": "^7.11.5",
"#babel/preset-react": "^7.10.4",
"#babel/preset-typescript": "^7.10.4",
"#types/react": "^16.9.49",
"#types/react-dom": "^16.9.8",
"babel-jest": "^26.6.3",
"babel-loader": "^8.1.0",
"cross-env": "^7.0.2",
"css-loader": "^4.3.0",
"enzyme": "^3.0.0",
"enzyme-adapter-react-16": "^1.0.0",
"enzyme-to-json": "^3.0.1",
"file-loader": "^6.1.0",
"html-loader": "^1.3.0",
"html-webpack-plugin": "^4.5.0",
"identity-obj-proxy": "^3.0.0",
"jest": "^26.6.3",
"jest-cli": "^26.6.3",
"mini-css-extract-plugin": "^0.11.1",
"node-sass": "^4.14.1",
"raf": "^3.3.2",
"react": "^16.13.1",
"react-dom": "^16.13.1",
"sass-loader": "^10.0.2",
"typescript": "^4.0.2",
"webpack": "^4.44.1",
"webpack-cli": "^3.3.12",
"webpack-dev-server": "^3.11.0"
},
"jest": {
"moduleNameMapper": {
"\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/src/tests/__mocks__/fileMock.js",
"\\.(scss|css|less)$": "<rootDir>/src/tests/__mocks__/styleMock.js"
}
"transform": {
"\\.js?x$": "<rootDir>/node_modules/babel-jest"
}
}
}
Inside Webpack.config.js (showing partial)
module: {
rules: [
{
test: /\.s[ac]ss$/i,
use: [MiniCssExtractPlugin.loader, "css-loader", "sass-loader"]
}
]
},
Inside . babelrc file
{
"presets": ["#babel/react", "#babel/env"]
}
Looks like you forget to mock scss file during test despite having already had css|less files there.
To fix that, you have to add scss as part of current style file pattern:
package.json
{
"jest": {
"moduleNameMapper": {
// ...
"\\.(css|less|scss)$": "<rootDir>/src/tests/__mocks__/styleMock.js"
}
}
}
Update
You're currently input jest cli with --config=jest.config.json which is json file which is wrong (it must be js file) that ended up the issue.
The right one should be:
jest --config=jest.config.js // `js` not `json`
But you have 2 config one in jest.config.js and jest area in package.json file. Please try to use one place instead by either remove --config=jest.config.js in CLI or move entire jest block into the config file.

Updating Vuetify but sass loader doesn't work

I am new to vuetify and I am trying upgrade to v2.1.3 but sass loader doesn't work. I read all the documentation but my English is not very good, I can't fix this problem.
Actually, I can update vuetify and it works. I can see the new vuetify and I run other things but my Project doesn't see sass. This is my problem
My package .json;
{
"name": "arkmanweb",
"version": "1.9.4",
"private": true,
"scripts": {
"serve": "vue-cli-service serve",
"build": "vue-cli-service build",
"lint": "vue-cli-service lint"
},
"dependencies": {
"#syncfusion/ej2-vue-grids": "^17.3.19",
"axios": "^0.18.0",
"css-loader": "^3.2.1",
"echarts": "^4.2.0-rc.2",
"luxon": "^1.19.3",
"print-js": "^1.0.52",
"quill": "^1.3.6",
"register-service-worker": "^1.0.0",
"sass": "^1.23.7",
"sass-loader": "^8.0.0",
"save": "^2.3.2",
"underscore": "^1.8.3",
"vee-validate": "^2.0.4",
"vue": "^2.5.13",
"vue-i18n": "^8.4.0",
"vue-moment": "^3.2.0",
"vue-router": "^3.0.1",
"vuetify": "^2.1.13",
"vuex": "^3.0.1",
"webpack": "^4.41.2",
},
"devDependencies": {
"#vue/cli-plugin-babel": "^3.0.0-alpha.8",
"#vue/cli-plugin-eslint": "^3.0.0-alpha.8",
"#vue/cli-plugin-pwa": "^3.0.0-alpha.8",
"#vue/cli-service": "^3.0.0-alpha.8",
"deepmerge": "^4.2.2",
"fibers": "^4.0.2",
"less-loader": "4.1.0",
"style-loader": "0.23.1",
"vue-template-compiler": "^2.5.13",
"webpack-cli": "^3.1.2"
},
"babel": {
"presets": [
"#vue/app"
]
},
"eslintConfig": {
"extends": [
"plugin:vue/essential",
"eslint:recommended"
]
},
"postcss": {
"plugins": {
"autoprefixer": {}
}
},
"browserslist": [
"> 1%",
"last 2 versions",
"not ie <= 8"
]
}
This is my main js:
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import Vuetify from 'vuetify'
import './registerServiceWorker'
import VueResource from 'vue-resource'
import '../src/assets/css/custom.css'
import { i18n } from '#/plugins/i18n'
import 'vuetify/dist/vuetify.min.css'
Vue.use(VueResource)
const opts = {
theme: { disable: true }
}
Vue.use(Vuetify)
import auth from '../src/api/auth'
auth.checkAuth()
Vue.router = router
Vue.config.productionTip = false
new Vue({
router,
vuetify:new Vuetify(opts),
store,
i18n,
render: h => h(App)
}).$mount('#app')
This is App.vue I am importing sass here but doesn't work:
<style lang="sass">
#import '../node_modules/vuetify/src/styles/main.sass';
</style>
What's wrong? Thank you for your help.
This is my error:
error in ./src/App.vue?vue&type=style&index=0&lang=sass&
Module build failed (from ./node_modules/sass-loader/dist/cjs.js):
ValidationError: Invalid options object. Sass Loader has been initialised using an options object that does not match the API schema.
- options has an unknown property 'data'. These properties are valid:
object { implementation?, sassOptions?, prependData?, sourceMap?, webpackImporter? }
Its hard to tell based on information you provided but it seems you upgraded sass-loader to version 8.0.0 as part of the upgrade of Vuetify
There is a breaking change in 8.0.0 release of sass-loader in how the configuration should look like - all the options for the underlying sass processor (Node Sass or Dart Sass) needs now to be moved into sassOptions

How to do server side rendering in react despite all react router version conflicts?

I am trying to server-side rendering with react and react-router-dom I've done this before but with the new version, it is throwing me an error You should not use Switch outside a Router I think it is a version conflict but is there a solution (react-router-config - You should not use outside a (it is inside a Router!)).
server.js
import express from 'express';
import React from 'react';
import ReactDOMServer from 'react-dom/server';
import App from '../client/src/AppRoutes';
import { StaticRouter } from 'react-router-dom';
import { renderRoutes } from 'react-router-config'
const app = express();
app.get('*', (req, res) => {
const routerContext = {};
res.send(`
<!doctype html>
<html lang="en">
<head>SSR</head>
<body>
<div id="root">${ReactDOMServer.renderToString(
<StaticRouter location={req.url} context={routerContext}>
<div>{renderRoutes(App)}</div>
</StaticRouter>
)}</div>
<!-- <script src="/dist/main.js"></script>-->
</body>
</html>
`);
});
app.listen(3000, (error) => {
if (error) {
return console.log('something bad happened', error);
}
console.log("listening on " + 3000 + "...");
});
AppRoutes.js
import PageA from './Container/PageA';
import PageB from './Container/PageB';
import Home from './Container/Home'
import MainPage from './Container/MainPage';
export default [
{
...MainPage,
routes:[
{
...Home,
path:'/',
exact:true
},
{
...PageA,
path:'/a',
exact:true
},
{
...PageB,
path:'/b',
exact:true
}
]
}
]
package.json
{
"name": "reactSSRwithCodeSplitting",
"version": "1.0.0",
"description": "",
"main": "server/server.js",
"scripts": {
"test": "babel-node server/index.js",
"start": "nodemon server/index.js",
"build": "babel server --out-dir ./dist --source-maps",
"serve": "node ./dist/index.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.17.1",
"react": "^16.9.0",
"react-dom": "^16.9.0",
"react-loadable": "^5.5.0",
"react-router-config": "^5.0.1",
"react-router-dom": "^5.0.1"
},
"devDependencies": {
"#babel/cli": "^7.5.5",
"#babel/core": "^7.5.5",
"#babel/node": "^7.5.5",
"#babel/plugin-syntax-dynamic-import": "^7.2.0",
"#babel/preset-env": "^7.5.5",
"#babel/preset-react": "*",
"#babel/register": "^7.5.5",
"chai": "^4.2.0",
"nodemon": "^1.19.1"
}
}
Quick fix:
Remove your node_modules
Add "react-router": "^5.0.1" to your package.json
Re-install with npm install.
Ensure that react-router, react-router-config, react-router-dom are in the same version.
What is wrong?
When I try to reproduce your error, I figure out that your package.json in the question is missing react-router dependency, which makes me unable to start the server.
And from your story, I guess that you have another version of react-router in your node_modules, which is out of sync with react-router-config and react-router-dom version 5.0.1.
So I try to reproduce the problem with this:
"react-router": "^4.3.0",
"react-router-config": "^5.0.1",
"react-router-dom": "^5.0.1"
Which will lead to the problem you mentioned.

Module not found: Can't resolve 'autosuggest-highlight/match'

I am trying to compile my react website. But whenever I try to build, it fails. I keep getting
Module not found: Can't resolve 'autosuggest-highlight/match'
I have react-drawer just outside where this file is, as well as my npm and node modules up to date. Every time I try to update the files, or make a change, it doesn't even start to compile and crashes at "react-script start".
This is the code for the page that crashed:
import React from 'react';
import Autosuggest from 'react-autosuggest';
import * as AutosuggestHighlightMatch from 'autosuggest-highlight/match';
import * as AutosuggestHighlightParse from 'autosuggest-highlight/parse';
import ApiRequest from './ApiRequest.js';
class Search extends React.Component {
componentDidMount() {
new ApiRequest('GET', '/clientlist').send((res, people) => {
if (res.status == 200) {
this.setState({people});
} else if (res.status == 401 || res.status == 403) {
console.log('authentication error');
}
});
}
constructor() {
super();
this.state = {
value: '',
suggestions: [],
people: [],
selection: ''
};
this.renderSuggestion = (suggestion, {query}) => {
const suggestionText = `${suggestion.name}`;
const matches = AutosuggestHighlightMatch(suggestionText,query);
const parts = AutosuggestHighlightParse(suggestionText, matches);
return (
<span className='suggestion-content '
style={{backgroundImage: `url(${suggestion.profileimg || 'http://s3.amazonaws.com/37assets/svn/765-default-avatar.png'})`}}>
<span className="name">
{
parts.map((part, index) => {
const className = part.highlight ? 'highlight' : null;
return (
<span className={className} key={index}>{part.text}</span>
);
})
}
</span>
</span>
)
};
This is the image of my folder hierarchy:
Here is my Package.Json
{
"name": "medimo",
"version": "0.1.0",
"private": true,
"dependencies": {
"autosuggest-highlight": "^3.1.0",
"chart.js": "^2.6.0",
"es6-object-assign": "^1.1.0",
"history": "^1.17.0",
"moment": "^2.18.1",
"parse-react": "^0.5.2",
"parse-server": "^2.5.3",
"parse5": "^3.0.2",
"postcss": "^6.0.9",
"postcss-cssnext": "^3.0.2",
"react": "^15.6.1",
"react-autosuggest": "^9.3.2",
"react-chartjs-2": "^2.5.7",
"react-dom": "^15.6.1",
"react-dropdown": "^1.2.5",
"react-image": "^1.0.1",
"react-motion-drawer": "file:../custom-deps/react-motion-drawer",
"react-router": "^4.1.2",
"react-router-dom": "^4.1.2",
"react-scripts": "1.0.10",
"react-sortable-hoc": "^0.6.7",
"react-tabs": "^1.1.0",
"socket.io-client": "^2.0.3",
"socket.io-react": "^1.2.0",
"utils": "^0.3.1"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject"
},
"proxy": "http://localhost:3001",
"devDependencies": {
"babel-core": "^6.25.0",
"babel-loader": "^7.1.1",
"babel-preset-react": "^6.24.1",
"html-webpack-plugin": "^2.30.1",
"postcss-loader": "^2.0.6",
"webpack": "^3.4.1",
"webpack-dev-server": "^2.6.1"
}
}
I had the same problem with the exact same package funnily enough.
This is what I have that fixed it:
import AutosuggestHighlightMatch from "autosuggest-highlight/umd/match";
import AutosuggestHighlightParse from "autosuggest-highlight/umd/parse";
The dependency needs to be added it seems like:
npm i autosuggest-highlight
What solved the problem for me was to:
Delete node_modules directory
run npm install
Check-in official page document, following the way of import also working
import AutosuggestHighlightMatch from "autosuggest-highlight/match";
import AutosuggestHighlightParse from "autosuggest-highlight/parse";

Categories

Resources