I'm trying to learn how to do unit testing with React and jest. I've run into the following error:
Unexpected token import
Here are my babel presets:
{
"presets": ["es2015", "stage-0", "react"],
"env": {
"test": {
"plugins": ["transform-es2015-modules-commonjs"]
}
}
}
Here is the file i'm trying to test:
import jest from 'jest';
import React from 'react';
import { shallow } from 'enzyme';
import Step from '../src/components/step.js';
const wrapper = shallow(<Step />);
wrapper.find('a').simulate('click', { preventDefault() {} });
and here is my package.json:
{
"name": "react-simple-boilerplate",
"version": "1.0.0",
"description": "Simple and lightweight Boilerplate for ReactJS projects",
"scripts": {
"lint": "eslint src",
"start": "node server.js",
"test": "jest"
},
"devDependencies": {
"babel-core": "^6.24.1",
"babel-loader": "^7.0.0",
"babel-plugin-transform-es2015-modules-commonjs": "^6.26.0",
"babel-preset-es2015": "^6.24.1",
"babel-preset-react": "^6.24.1",
"babel-preset-stage-0": "^6.24.1",
"css-loader": "^0.28.0",
"enzyme": "^3.2.0",
"enzyme-adapter-react-16": "^1.1.0",
"eslint": "^3.19.0",
"eslint-plugin-react": "^6.10.3",
"jest": "^21.2.1",
"node-sass": "^4.5.2",
"react-addons-test-utils": "^15.6.2",
"sass-loader": "^6.0.3",
"style-loader": "^0.16.1",
"webpack": "^2.4.1",
"webpack-dev-server": "^2.4.4"
},
"dependencies": {
"babel-loader": "^7.0.0",
"react": "^15.5.4",
"react-dom": "^15.5.4"
},
"main": "server.js"
}
Have no idea why its giving me this message?
It looks like babel-jest is missing among your dependencies. That's why jest is not running babel on your ES6+ code before executing tests.
I'm pretty sure you need to add your babel presets to test as well, jest sets the env variable to test.
So...
"test": {
"plugins": ["transform-es2015-modules-commonjs"],
"presets": ["es2015", "react", "stage-0"]
}
Related
I have downloaded the npm i --save esri-loader #esri/react-arcgis but why is it i cant load the map? did i miss something?
import React from 'react';
import Map from '../../component/Map/Map.js'
const HomePage = () => {
return (
<div>
<Map/>
</div>
);
};
export default HomePage;
component/Map/Map.js
import React , {useRef,useEffect} from 'react';
import {loadModules} from "esri-loader";
function Map() {
const MapElement=useRef(null)
useEffect(()=>{
let view;
loadModules(["esri/views/MapView", "esri/WebMap"],{
css:true
}).then(([MapView, WebMap])=>{
const webmap= new WebMap({
basemap:'topo-vector'
})
view = new MapView({
map:webmap,
center:[],
zoom:8,
container:MapElement.current
})
})
return()=>{
if(!!view){
view.destroy()
view=null
}
}
})
return (
<div style={{height:800}} ref={MapElement}>
</div>
)
}
export default Map
the error i get
the reference i used for this https://www.youtube.com/watch?v=0RC1Xf_0UUk
package.json
{
"name": "#country/app", "private": true, "scripts": {
"start": "webpack serve",
"start:standalone": "webpack serve --port 9003 --env standalone",
"build": "concurrently yarn:build:*",
"build:webpack": "webpack --mode=production",
"analyze": "webpack --mode=production --env analyze",
"lint": "eslint src --ext js",
"format": "prettier --write .",
"check-format": "prettier --check .",
"test": "cross-env BABEL_ENV=test jest",
"watch-tests": "cross-env BABEL_ENV=test jest --watch",
"prepare": "husky install",
"coverage": "cross-env BABEL_ENV=test jest --coverage" }, "devDependencies": {
"#arcgis/webpack-plugin": "^4.20.0",
"#babel/core": "^7.15.0",
"#babel/eslint-parser": "^7.15.0",
"#babel/plugin-transform-runtime": "^7.15.0",
"#babel/preset-env": "^7.15.0",
"#babel/preset-react": "^7.14.5",
"#babel/runtime": "^7.15.3",
"#testing-library/jest-dom": "^5.14.1",
"#testing-library/react": "^12.0.0",
"babel-jest": "^27.0.6",
"concurrently": "^6.2.1",
"cross-env": "^7.0.3",
"eslint": "^7.32.0",
"eslint-config-prettier": "^8.3.0",
"eslint-config-react-important-stuff": "^3.0.0",
"eslint-plugin-prettier": "^3.4.1",
"husky": "^7.0.4",
"identity-obj-proxy": "^3.0.0",
"jest": "^27.4.3",
"jest-cli": "^27.4.3",
"prettier": "^2.3.2",
"pretty-quick": "^3.1.1",
"webpack": "^5.51.1",
"webpack-cli": "^4.8.0",
"webpack-config-single-spa-react": "^4.0.0",
"webpack-dev-server": "^4.0.0",
"webpack-merge": "^5.8.0" }, "dependencies": {
"#esri/react-arcgis": "^5.1.0",
"#material-ui/styles": "^4.11.4",
"#mui/styles": "^5.2.2",
"#reach/router": "^1.3.4",
"arcgis-js-api": "^4.21.2",
"esri-loader": "^3.3.0",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"single-spa-react": "^4.3.1" }, }
Sorry for not directly responding to your described error, but I would not use esri-loader with newer versions of ArcGIS for JavaScript API. Why not npm as ES modules which do not require a separate script loader?
Build with ES Module
This way you can do simple imports like this:
import WebMap from "#arcgis/core/WebMap";
Here are the initial setup instructions:
Install instructions
Finally, here is a sample react app from Esri using exactly that:
Esri React App example
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.
Hello I recently started working with TypeScript, I decided to migrate a WebComponent I started with the base of the component I am trying to import a polyfill (construct-style-sheets-polyfill) that extends the functionality of the CSSStyleSheet class but I can't make TypeScript recognize the "replaceSync" method that is added in the Polyfill
How can I make TypeScript update the class definition with the Polyfill methods?
import {patch, elementOpen, elementClose} from 'incremental-dom';
import '#webcomponents/custom-elements'
import 'construct-style-sheets-polyfill';
import * as reset_style from './reset.scss';
const sheet:CSSStyleSheet = new CSSStyleSheet();
sheet.replaceSync(reset_style);
Error:(7, 8) TS2339: Property 'replaceSync' does not exist on type
'CSSStyleSheet'.
package.json
{
"scripts": {
"dev": "webpack --mode development",
"build": "webpack --mode production"
},
"devDependencies": {
"#babel/cli": "^7.11.6",
"#babel/core": "^7.11.6",
"#babel/plugin-proposal-class-properties": "^7.10.4",
"#babel/preset-env": "^7.11.5",
"#babel/preset-typescript": "^7.10.4",
"babel-loader": "^8.1.0",
"html-webpack-plugin": "^4.5.0",
"node-sass": "^4.14.1",
"sass-loader": "^10.0.3",
"style-loader": "^2.0.0",
"terser-webpack-plugin": "^4.2.3",
"ts-loader": "^8.0.4",
"typescript": "^4.0.3",
"typings-for-css-modules-loader": "^1.7.0",
"webpack": "^4.44.2",
"webpack-cli": "^3.3.12",
"webpack-dev-server": "^3.11.0"
},
"dependencies": {
"construct-style-sheets-polyfill": "^2.4.2",
"incremental-dom": "^0.7.0"
}
}
tsconfig.json
{
"include": [
"src/**/*.ts",
"declarations.d.ts"
],
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"strict": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
}
}
What you want to do is merge your interfaces.
In your declarations.d.ts file, include the following
interface CSSStyleSheet {
replaceSync(reset_style: any): void
}
For some reason my ide is printing out 'Unexpected token <. Remember, adjacent JSX elements must be wrapped in an enclosing parent tag' for the following react code. I don't understand why it's printing that error since the component it's referring to is wrapped in an enclosing parent tag the <TableBody> tag specifically.
/* #flow */
import React from 'react'
import TableBody from '#material-ui/core/TableBody'
import Roster from './roster.jsx'
import type { MembersType } from '../../typeDefs/MembersType.js'
type RanksType = {
_id: string | number,
rankName: string,
members: Array<MembersType>
};
export default (props: {
members: MembersType
}) => (
<TableBody>
{props.members.map(({
_id,
rankName,
members,
}: RanksType) => (
<Roster <---specifically refering to this element
key={_id}
rank={rankName}
members={members}
/>
))}
</TableBody>
)
Package.json
{
"name": "novacms",
"private": true,
"scripts": {
"start": "meteor --settings settings-production.json --port $IP:$PORT",
"dev": "meteor --settings settings-development.json --port $IP:$PORT",
"test": "meteor test --driver-package cultofcoders:mocha --port $IP:$PORT"
},
"dependencies": {
"#babel/runtime": "^7.0.0-beta.42",
"#novacms/assign": "^1.0.0",
"#novacms/dependancy-injector": "^1.0.0",
"#novacms/event-store": "^1.0.0",
"#novacms/extend": "^1.0.0",
"#novacms/extendschema": "^1.0.1",
"#novacms/has": "^1.0.0",
"#novacms/pipe": "^1.0.0",
"#novacms/type-check": "^1.0.0",
"#material-ui/core": "^1.0.0-rc.1",
"babel-plugin-syntax-dynamic-import": "^6.18.0",
"babel-plugin-transform-optional-chaining": "^7.0.0-beta.3",
"bcrypt-nodejs": "0.0.3",
"event-emitter": "^0.3.5",
"faker": "^4.1.0",
"lodash": "^4.17.5",
"md5": "^2.2.1",
"meteor-apihelper": "^1.0.0",
"meteor-node-stubs": "^0.3.3",
"mobx": "^3.6.1",
"mobx-react": "^4.4.2",
"moment": "^2.21.0",
"npm": "^5.10.0",
"prettier": "^1.12.1",
"prop-types": "^15.6.1",
"react": "^16.3.0",
"react-dom": "^16.3.0",
"react-router": "^4.2.0",
"react-storybook": "^1.0.0",
"recompose": "^0.26.0",
"semantic-ui-css": "^2.3.1",
"semantic-ui-react": "^0.79.1",
"simpl-schema": "^1.4.2",
"simpl-schema-mockdoc": "^1.0.5",
"sinon": "^4.5.0",
"spacejam": "^1.6.1"
},
"devDependencies": {
"babel-eslint": "^8.2.3",
"babel-plugin-transform-class-properties": "^6.24.1",
"babel-plugin-transform-decorators": "^6.24.1",
"babel-plugin-transform-decorators-legacy": "^1.3.4",
"chai": "^4.1.2",
"eslint": "^4.19.1",
"eslint-config-airbnb": "^16.1.0",
"eslint-import-resolver-meteor": "^0.4.0",
"eslint-plugin-import": "^2.11.0",
"eslint-plugin-jsx-a11y": "^6.0.3",
"eslint-plugin-meteor": "^5.0.0",
"eslint-plugin-prettier": "^2.6.0",
"eslint-plugin-react": "^7.8.2",
"eslint-plugin-flowtype": "^2.46.3"
},
"parser": "babel-eslint"
}
VSCode config
{
"files.eol": "\r\n",
"editor.fontFamily": "'Fira Mono', Consolas, 'Courier New', monospace",
"eslint.workingDirectories": [
"./src",
"./client",
"./imports",
"./server"
],
"react.beautify.onSave": true,
"editor.tabSize": 2,
"files.trimTrailingWhitespace": true,
"javascript.validate.enable": false,
"javascript.format.enable": false,
}
.babelrc
{
"plugins": ["transform-decorators-legacy", "transform-class-properties", "syntax-dynamic-import"]
}
I had a very similar issue.
Firstly delete (rename) your .babelrc file which you use (remove where ever you set it).
If storybook can't find that file, then it will use its own settings. This worked for me to prove that it was that file that caused the issue.
If this is the same for you then create a new .babelrc file, and place it into the storybook folder. Storybook will now use this and your project can continue to use the existing one.
The tricky part is finding the config setting in you existing .babelrc file that is breaking storybook - for me it was the react-hot-load/babel, but you don't have that listed.
My file ended up with only #babel/plugin-proposal-class-properties and #babel/plugin-proposal-rest-spread for plugins.
I am trying to run a simple jest and enzyme test against a react component and test throws: ReferenceError: React is not defined. I followed all simple tutorials on jest and react testing but all of them resulted in the same exception. I used npm test and result was the same as yarn test, React not defined. I am confused. Any help would be appreciated.
Checkbox.test.jsx: simple test
import { shallow } from 'enzyme';
import sinon from 'sinon';
import Checkbox from './Checkbox';
describe('<Checkbox />', () => {
it('should render three <Checkbox /> components', () => {
const wrapper = shallow(<Checkbox />);
expect(wrapper.prop('title')).toEqual('Events — Event Radar');
});
});
Console log
$ yarn test
FAIL src\components\ReusableComponents\Checkbox.test.jsx (5.248s)
<Checkbox />
× should render three <Checkbox /> components (4ms)
● <Checkbox /> › should render three <Checkbox /> components
ReferenceError: React is not defined
at Object.<anonymous> (src/components/ReusableComponents/Checkbox.test.jsx:8:40)
Test Suites: 1 failed, 1 total
Tests: 1 failed, 1 total
Snapshots: 0 total
Time: 10.517s
Ran all test suites.
error Command failed with exit code 1.
package.json
{
"name": "mi-benchmarking-frontend",
"version": "0.1.0",
"private": true,
"dependencies": {
"axios": "^0.17.0",
"classnames": "^2.2.5",
"history": "^4.7.2",
"prop-types": "^15.6.0",
"react": "^16.0.0",
"react-bootstrap": "^0.31.5",
"react-bootstrap-table": "^4.1.1",
"react-dom": "^16.0.0",
"react-logger": "^1.1.0",
"react-pagination-table": "^1.1.0",
"react-redux": "^5.0.6",
"react-router": "^3.2.0",
"react-router-redux": "^4.0.8",
"react-scripts": "1.0.14",
"react-simple-paginate": "^1.1.0",
"react-table": "^6.6.0",
"redux": "^3.7.2",
"redux-logger": "^3.0.6",
"redux-thunk": "^2.2.0"
},
"devDependencies": {
"autoprefixer": "^6.3.6",
"babel-core": "^6.26.0",
"babel-eslint": "^6.0.4",
"babel-jest": "^21.2.0",
"babel-loader": "^6.2.4",
"babel-plugin-react-require": "^3.0.0",
"babel-plugin-syntax-object-rest-spread": "^6.13.0",
"babel-plugin-transform-object-spread-inline": "0.0.2",
"babel-polyfill": "^6.8.0",
"babel-preset-es2015": "^6.6.0",
"babel-preset-react": "^6.5.0",
"babel-preset-stage-0": "^6.5.0",
"clean-webpack-plugin": "^0.1.13",
"copy-webpack-plugin": "^4.0.0",
"css-loader": "^0.23.1",
"enzyme": "^3.1.0",
"enzyme-adapter-react-16": "^1.0.2",
"eslint": "^3.19.0",
"eslint-loader": "^1.5.0",
"eslint-plugin-babel": "^4.1.2",
"eslint-plugin-react": "^7.1.0",
"extract-text-webpack-plugin": "^3.0.2",
"file-loader": "^1.1.5",
"html-webpack-plugin": "^2.16.1",
"jest": "^21.2.1",
"jest-enzyme": "^4.0.1",
"json-loader": "^0.5.4",
"postcss-loader": "^0.9.1",
"redux-devtools": "^3.4.0",
"sinon": "^4.0.2",
"style-loader": "^0.13.1",
"url-loader": "^0.5.7",
"webpack": "2.6.1",
"webpack-dev-server": "2.5.0",
"webpack-manifest-plugin": "1.1.0"
},
"scripts": {
"start": "npm run build:dev",
"build:dev": "webpack-dev-server --inline --history-api-fallback",
"build:test": "webpack --define process.env.NODE_ENV='test'",
"build:stage": "webpack --define process.env.NODE_ENV='stage'",
"build:prod": "webpack --define process.env.NODE_ENV='production'",
"eject": "react-scripts eject",
"test": "jest",
"test:watch": "jest --watch",
"test:coverage": "jest --coverage"
},
"jest": {
"setupTestFrameworkScriptFile": "./node_modules/jest-enzyme/lib/index.js"
}
}
Import React in your test and the error should disappear:
import React from 'react';
I tried removing this import in one of my tests and I got the same error you mentioned.
I hope this helps.