How to use babel-jest to transpile tests - reactjs

I'm writing tests for a React application and run into an issue while compiling classes that i import in my test files. When running the test suite
i get the following error:
Jest encountered an unexpected token
This usually means that you are trying to import a file which Jest cannot parse, e.g. it's not plain JavaScript.
By default, if Jest sees a Babel config, it will use that to transform your files, ignoring "node_modules".
Here's what you can do:
• To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
• If you need a custom transformation specify a "transform" option in your config.
• If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.
You'll find more details and examples of these config options in the docs:
https://jestjs.io/docs/en/configuration.html
Details:
/node_modules/react-redux/es/connect/connect.js:5
import connectAdvanced from '../components/connectAdvanced';
^^^^^^
I have tried to use babel-jest to transpile using the transform property and the modulePathIgnorePatterns. My jest.config.json looks like:
{
"moduleNameMapper": {
".+\\.(css|styl|less|sass|scss|png|jpg|ttf|woff|woff2)$": "identity-obj-proxy"
},
"setupFiles": [
"raf/polyfill",
"<rootDir>/test/testSetup.js"
],
"transform": {
"^.+\\.jsx?$": "babel-jest"
}
}
my babel.rc file (its in the root directory)
{
"presets": [ "react", "es2015", "stage-2" ],
"plugins": [
"transform-class-properties",
"transform-object-rest-spread",
]
}
I have the following packages in my package.json:
"devDependencies": {
"babel-cli": "^6.26.0",
"babel-core": "^6.26.3",
"babel-eslint": "^8.2.1",
"babel-loader": "^7.1.2",
"babel-plugin-transform-object-rest-spread": "^6.26.0",
"babel-preset-env": "^1.7.0",
"babel-preset-es2015": "^6.24.1",
"babel-preset-react": "^6.24.1",
"babel-preset-stage-2": "^6.24.1",
"enzyme": "^3.6.0",
"enzyme-adapter-react-16": "^1.5.0",
"eslint": "^5.3.0",
"eslint-plugin-react": "^7.10.0",
"identity-obj-proxy": "^3.0.0",
"jest": "^23.5.0",
"babel-jest": "^23.6.0"
"mkdirp": "^0.5.1",
"prettier": "^1.13.7",
"prettier-eslint": "^8.8.2",
"prop-types": "^15.6.0",
"react-test-renderer": "^16.5.0",
"webpack": "^4.16.5",
"webpack-cli": "^3.1.0",
"webpack-dev-server": "^3.1.5",
"webpack-merge": "^4.1.4",
"yargs": "^12.0.1"
},
"dependencies": {
"axios": "^0.18.0",
"babel-polyfill": "^6.26.0",
"css-loader": "^1.0.0",
"eventing-bus": "^1.3.3",
"filesize": "^3.6.1",
"i18next": "^11.5",
"node-sass": "^4.8.3",
"react": "^16.4",
"react-circular-progressbar": "^1.0.0",
"react-dom": "^16.4",
"react-redux": "^5.0",
"react-truncate": "^2.4.0",
"redux": "^4.0",
"sass-loader": "^7.1.0",
"style-loader": "^0.22.1"
}
Who knows how i can modify my jest.config or .babelrc file so that my tests will compile without problem? Thanks in advance.

Your problem is: js files from /node_modules are not compiled by default.
It is totaly fine when you run your code in browser (that is exactly why such modules are not compiled because you have no need for that).
But jest runs using Node which doesn't understand import syntax. The best solution is to enable babel transpilation of node_modules when you run tests.
{"env": {
"development": {
"plugins": ["transform-es2015-modules-commonjs"]
},
"test": {
"plugins": ["transform-es2015-modules-commonjs"]
}
}}
Also use --no-cache when runing jest while fixing such problems.

Related

Reactjs - /dist folder has only 2 files - bundle.js and bundle.js.map - doesn't include any other files

I have a reactjs app - which is running well in dev environment. I mean, when I use
npm start
It's running in localhost:8080 without any issues.
When I try to execute the same with below command, to generate a distribution folder for static hosting, somewhere in AWS S3. That's where the problem.
npm run build
Below is my output folder structure when I execute the above command:
dist
bundle.js
bundle.js.map
public
index.html
I have gone through these posts (regarding warning which I'm getting related to bundle.js file sizes & this link) and did modify as per the suggestion, but I haven't got the desired outcome.
Below is my package.json for reference:
{
"name": "react-starter",
"version": "1.1.5",
"description": "example",
"main": "dist/bundle.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "webpack-dev-server --config ./webpack.dev.js",
"build": "webpack --max_old_space_size=4096 --config ./webpack.prod.js --progress --profile --colors"
},
"homepage": ".",
"keywords": [
"react"
],
"devDependencies": {
"babel-cli": "^6.26.0",
"babel-core": "^6.26.3",
"babel-eslint": "^10.0.2",
"babel-loader": "^7.1.5",
"babel-plugin-transform-class-properties": "^6.24.1",
"babel-plugin-transform-object-rest-spread": "^6.26.0",
"babel-preset-env": "^1.7.0",
"babel-preset-react": "^6.24.1",
"clean-webpack-plugin": "^0.1.19",
"css-loader": "^3.2.0",
"dotenv": "^6.2.0",
"eslint": "^5.16.0",
"eslint-config-airbnb": "^17.1.0",
"eslint-plugin-import": "^2.17.3",
"eslint-plugin-jsx-a11y": "^6.2.1",
"eslint-plugin-react": "^7.13.0",
"eslint-plugin-react-hooks": "^1.6.0",
"file-loader": "^1.1.11",
"node-sass": "^4.12.0",
"react": "^16.8.6",
"react-dom": "^16.8.6",
"sass-loader": "^7.1.0",
"style-loader": "^0.21.0",
"stylelint": "^9.10.1",
"stylelint-config-standard": "^18.3.0",
"uglifyjs-webpack-plugin": "^2.1.3",
"webpack": "^4.34.0",
"webpack-cli": "^3.3.4",
"webpack-dev-server": "^3.7.1",
"webpack-merge": "^4.1.4"
},
"dependencies": {
"bootstrap": "^4.3.1",
"i18next": "^16.0.0",
"i18next-browser-languagedetector": "^3.0.1",
"konva": "^2.5.1",
"normalizr": "^3.4.0",
"prop-types": "^15.7.2",
"react-hot-loader": "^4.11.1",
"react-i18next": "^10.11.1",
"react-icons": "^3.7.0",
"react-konva": "^16.8.6",
"react-player": "^1.11.1",
"react-scroll": "^1.7.12",
"reactstrap": "^6.5.0"
},
"peerDependencies": {
"react": "^16.8.6",
"react-dom": "^16.8.6"
}
}
webpack.prod.js is below:
const path = require('path');
const merge = require('webpack-merge');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const common = require('./webpack.common.js');
module.exports = merge(common, {
entry: 'apps/index.js',
mode: 'production',
devtool: 'source-map',
output: {
path: path.resolve(__dirname, 'dist/'),
publicPath: '/dist/',
filename: 'bundle.js',
libraryTarget: 'commonjs2',
},
plugins: [
new CleanWebpackPlugin(['dist/*.*']),
],
externals: {
react: 'react',
'react-dom': 'react-dom',
},
});
I also noticed some deprecations in the library which I'm trying to integrate with. I've installed the missing peer dependencies. I've reported the issues with the library here.
I believe to upload it to S3, we should have all necessary files in the dist or public folder along with index.html which would be added as a prefix in S3 from where the app gets the entry point.
Any help on this would be highly appreciated. Also, I would be ready to provide any additional information.
Looking at your package.json file it seems you haven't used create-react-app.
I suggest to simply create a new React.js app using it and copy the content of your app in the newly created. It's easy and it works.
Hope this helps.
Just getting things working is not enough. You should go through a simple guide to setup things step-by-step like these
creating-a-production-ready-webpack-4-config-from-scratch
react-boilerplate using WebPack 4
And try some simple boilerplate projects before messing with a complex one like these
react-boilerplate
react-webpack-boilerplate
And yes starting with create-react-app is also good as suggested by #Daniele Ricci and You can use react-scripts eject to understand what's going on under the hood.

Something in your build process is loading the wrong version

I am getting following error. Can't figure out solution. I found many post which looks duplicate here but, nothing work.
like: Requires Babel "7.0.0-0" but was loaded with "6.26.3"
node_modules#babel\helper-plugin-utils\lib\index.js
throw Object.assign(err, {
Error: Requires Babel "^7.0.0-0", but was loaded with "6.26.3". If you are sure you have a compatible version of #babel/core, it is likely that something in your build process is loading the wrong version. Inspect the stack trace of this error to look for the first entry that doesn't mention "#babel/core" or "babel-core" to see
what is calling Babel.
Here following is my package.json
"dependencies": {
"express": "^4.16.4",
"isomorphic-fetch": "^2.2.1",
"react": "^16.6.3",
"react-dom": "^16.6.3",
"react-redux": "^5.1.1",
"react-router": "^4.3.1",
"react-router-config": "^1.0.0-beta.4",
"react-router-dom": "^4.3.1",
"redux": "^4.0.1",
"redux-thunk": "^2.3.0"
},
"devDependencies": {
"#babel/cli": "^7.2.3",
"#babel/core": "^7.2.2",
"#babel/plugin-proposal-class-properties": "^7.2.0",
"#babel/plugin-transform-runtime": "^7.2.0",
"#babel/preset-env": "^7.3.1",
"#babel/preset-react": "^7.0.0",
"babel-core": "^7.0.0-bridge.0",
"babel-jest": "^24.0.0",
"babel-loader": "^7.1.5",
"css-loader": "^1.0.1",
"cypress": "^3.1.3",
"enzyme": "^3.8.0",
"enzyme-adapter-react-16": "^1.7.1",
"enzyme-to-json": "^3.3.5",
"extract-text-webpack-plugin": "^4.0.0-beta.0",
"html-webpack-plugin": "^3.2.0",
"jest": "^24.0.0",
"jest-fetch-mock": "^2.0.1",
"json-loader": "^0.5.7",
"nodemon": "^1.18.9",
"npm-run-all": "^4.1.5",
"open": "0.0.5",
"redux-devtools": "^3.4.2",
"redux-mock-store": "^1.5.3",
"regenerator-runtime": "^0.13.1",
"style-loader": "^0.23.1",
"uglifyjs-webpack-plugin": "^2.0.1",
"webpack": "^4.26.1",
"webpack-cli": "^3.1.2",
"webpack-dev-server": "^3.1.14",
"webpack-node-externals": "^1.7.2"
},
"babel": {
"presets": [
"#babel/preset-env",
"#babel/preset-react"
],
"plugins": [
"#babel/plugin-transform-runtime",
"#babel/plugin-proposal-class-properties"
]
}
I am getting on npm start.
"start": "webpack -d && nodemon --exec babel-node ./server"
Found it :-)
I noticed that babel-node is not among your dependencies, therefore you must be using a global version of babel-node, likely version 6... So, just add the correct one into your devDependencies:
npm install --save-dev #babel/node
What is the output of npm ls babel-core? I realised that I have babel-cli#6.26.0 and babel-register#6.26.0, I removed them and installed #babel/cli and #babel/register
My config files look like this:
In package.json:
"resolutions": {
"babel-core": "7.0.0-bridge.0"
}
In .babelrc :
{
"presets": [
"#babel/preset-env",
"#babel/preset-react"
],
"plugins": [
"#babel/plugin-transform-runtime",
"#babel/plugin-proposal-class-properties",
"#babel/plugin-proposal-object-rest-spread",
"#babel/plugin-transform-async-to-generator"
]}
After all changes, it might be a good idea to delete your lock file and rebuild it.

JEST - unexpected token import while running test

Im writing tests for an application but i run into the following error when importing certain classes in my tests:
Jest encountered an unexpected token
This usually means that you are trying to import a file which Jest cannot parse, e.g. it's not plain JavaScript.
By default, if Jest sees a Babel config, it will use that to transform your files, ignoring "node_modules".
Here's what you can do:
• To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
• If you need a custom transformation specify a "transform" option in your config.
• If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.
You'll find more details and examples of these config options in the docs:
https://jestjs.io/docs/en/configuration.html
Details:
/node_modules/react-redux/es/connect/connect.js:5
import connectAdvanced from '../components/connectAdvanced';
^^^^^^
SyntaxError: Unexpected token import
9 | children: PropTypes.string.isRequired,
10 | translator: PropTypes.func.isRequired
11 | };
| ^
I have not written any tests yet, i only imported the component in my test file:
import {TheComponent} from '../src/components/the-component';
My jest.config.json looks like this:
{
"moduleNameMapper": {
".+\\.(css|styl|less|sass|scss|png|jpg|ttf|woff|woff2)$": "identity-obj-proxy"
},
"setupFiles": [
"raf/polyfill",
"<rootDir>/test/testSetup.js"
]
}
My .babelrc file looks like this and is in the root directory:
{
"presets": [ "react", "es2015", "stage-2" ],
"plugins": [
"transform-class-properties",
"transform-object-rest-spread",
]
}
My package.json file looks like this:
{
"name": "testError",
"version": "1.0.0",
"scripts": {
"test:jest": "jest --config=jest.config.json --watchAll"
},
"files": [
"dist",
"src"
],
"devDependencies": {
"babel-cli": "^6.26.0",
"babel-core": "^6.26.3",
"babel-eslint": "^8.2.1",
"babel-loader": "^7.1.2",
"babel-plugin-transform-object-rest-spread": "^6.26.0",
"babel-preset-env": "^1.7.0",
"babel-preset-es2015": "^6.24.1",
"babel-preset-react": "^6.24.1",
"babel-preset-stage-2": "^6.24.1",
"enzyme": "^3.6.0",
"enzyme-adapter-react-16": "^1.5.0",
"eslint": "^5.3.0",
"eslint-plugin-react": "^7.10.0",
"identity-obj-proxy": "^3.0.0",
"jest": "^23.5.0",
"mkdirp": "^0.5.1",
"prettier": "^1.13.7",
"prettier-eslint": "^8.8.2",
"prop-types": "^15.6.0",
"react-test-renderer": "^16.5.0",
"webpack": "^4.16.5",
"webpack-cli": "^3.1.0",
"webpack-dev-server": "^3.1.5",
"webpack-merge": "^4.1.4",
"yargs": "^12.0.1"
},
"dependencies": {
"axios": "^0.18.0",
"babel-polyfill": "^6.26.0",
"css-loader": "^1.0.0",
"eventing-bus": "^1.3.3",
"filesize": "^3.6.1",
"i18next": "^11.5",
"node-sass": "^4.8.3",
"react": "^16.4",
"react-circular-progressbar": "^1.0.0",
"react-dom": "^16.4",
"react-redux": "^5.0",
"react-truncate": "^2.4.0",
"redux": "^4.0",
"sass-loader": "^7.1.0",
"style-loader": "^0.22.1"
},
"main": "dist/main.js",
"module": "src/index.js"
}
I have tried to put several values in both the transformIgnorePatterns and transform properties in .babelrc but so for no luck.
Does anyone know how i can solve this issue? Any help will be appreciated.
As Mitch commented above,
I added the following to my jest.config file and it worked: "transformIgnorePatterns": [ "node_modules/(?!(react-redux|lodash-es)/)" ]

Unable to resolve path to module 'react'. (import/no-unresolved)

Seems like i am missing something here, it should work without errors but eslint keeps throwing the following:
Unable to resolve path to module 'react'. (import/no-unresolved)
Missing file extension for "react" (import/extensions)
when trying to import React from 'react'
here is some debug info:
package.json
{
"dependencies": {},
"devDependencies": {
"react": "16.3.2",
"react-dom": "16.3.2",
"#storybook/addon-actions": "^3.4.2",
"#storybook/addon-links": "^3.4.2",
"#storybook/addons": "^3.4.2",
"#storybook/react": "^3.4.2",
"babel-core": "^6.26.3",
"babel-eslint": "^8.2.3",
"babel-preset-env": "^1.6.1",
"babel-preset-react": "^6.24.1",
"babel-runtime": "^6.26.0",
"eslint": "^4.19.1",
"eslint-config-airbnb": "^16.1.0",
"eslint-config-prettier": "^2.9.0",
"eslint-plugin-import": "^2.11.0",
"eslint-plugin-jsx-a11y": "^6.0.3",
"eslint-plugin-react": "^7.7.0"
}
}
.eslintrc
{
"parser": "babel-eslint",
"extends": ["airbnb", "prettier"],
"env": {
"browser": true,
"node": true,
"es6": true
}
}
.babelrc
{
"presets": ["env", "react"]
}
editor: atom v1.26.1
Thanks.
If you're using React Native it may help to add .native.js as an allowed extension in your .eslintrc file.
Also, if you're using Typescript then .ts and .tsx will help too.
"settings": {
"import/resolver": {
"node": {
"extensions": [".ts", ".tsx", ".native.js"]
}
}
}
I had some problem i removed nodo_modules directory from project and run yarn install / npm install
I think it complains because react should be in dependencies:
{
"dependencies": {
"react": "16.3.2",
"react-dom": "16.3.2",
},
"devDependencies": {
"#storybook/addon-actions": "^3.4.2",
"#storybook/addon-links": "^3.4.2",
"#storybook/addons": "^3.4.2",
"#storybook/react": "^3.4.2",
"babel-core": "^6.26.3",
"babel-eslint": "^8.2.3",
"babel-preset-env": "^1.6.1",
"babel-preset-react": "^6.24.1",
"babel-runtime": "^6.26.0",
"eslint": "^4.19.1",
"eslint-config-airbnb": "^16.1.0",
"eslint-config-prettier": "^2.9.0",
"eslint-plugin-import": "^2.11.0",
"eslint-plugin-jsx-a11y": "^6.0.3",
"eslint-plugin-react": "^7.7.0"
}
}
I installed react and react-dom using npm i -E react react-dom trying to install the exact version which didn't install it correctly.
npm i react react-dom -D solved the problem.
This also happened to me. In my case, it was because I was running npm version 6, but a team member had installed a new library via npm version 7. Version 7 uses a new version for the lock file format.
Our solution was to make sure everyone was running the same npm version so that our package-lock.json files would be consistent.
Just comment out the import and run. Then again remove the comments. It worked for me.
try to add in eslintrc:
"rules": {
"import/no-unresolved": [2, { "devDependencies": true }],
...
}
I have experience with the same problem.
In my case, this error appear because I pull new update from the remote repository and it's bring new dependencies.
To solve this, I just install that dependencies with npm install

Jest Test Babel Error: Plugin/Preset files are not allowed to export objects

I'm using a very up-to-date (December 2017) stack of dependencies. As I try-out isomorphic react tests with Jest, the test suit keeps failing with the following error:
* Test suite failed to run
[BABEL] /__tests__/router.test.js: Plugin/Preset files are not allowed to
export objects, only functions.
Here are my dependencies:
"dependencies": {
"axios": "^0.17.1",
"babel-polyfill": "^6.26.0",
"cors": "^2.8.4",
"express": "^4.16.2",
"react": "^16.1.1",
"react-dom": "^16.1.1",
"react-router-dom": "^4.2.2"
},
"devDependencies": {
"#babel/core": "^7.0.0-beta.35",
"babel-cli": "^6.26.0",
"babel-core": "^7.0.0-bridge.0",
"babel-eslint": "^8.0.2",
"babel-jest": "^22.0.1",
"babel-loader": "^7.1.2",
"babel-preset-env": "^1.6.1",
"babel-preset-react": "^6.24.1",
"enzyme": "^3.2.0",
"enzyme-adapter-react-16": "^1.1.0",
"enzyme-to-json": "^3.2.2",
"eslint": "^4.11.0",
"eslint-plugin-react": "^7.5.1",
"html-webpack-plugin": "^2.30.1",
"jest": "^21.2.1",
"nodemon": "^1.11.0",
"parallelshell": "^3.0.2",
"react-test-renderer": "^16.2.0",
"regenerator-runtime": "^0.11.1",
"supertest": "^3.0.0",
"webpack": "^3.8.1",
"webpack-dev-server": "^2.9.4"
},
"peerDependencies": {
"babel-core": "^7.0.0-0"
}
.babelrc :
{
"presets": [
"env",
"react",
]
}
Does anyone have any insights as to why Jest won't run?
{
"presets": [
"env",
"react"
],
"test": [
"jest"
]
}
Add the last block of code for "test" to you babel.rc
Here is my .babelrc code for reference
{
"presets": [
"env",
"react"
],
"plugins": [
"transform-class-properties",
"transform-object-rest-spread"
],
"test": [
"jest"
]
}
Here is my output from the command-line
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 9.264s
Ran all test suites.
Done in 12.99s.
babel bridge is meant to cover any issues between 6 and 7
That is 100% not what the bridge package does. All it does is allow tools that use babel-core to pass through to #babel/core. The entire package is this single line of code.
If you are using #babel/core, you need to use plugins that work on Babel 7. That means babel-preset-react should be changed to #babel/preset-react and same for #babel/preset-env and your .babelrc should be:
{
"presets": [
"#babel/env",
"#babel/react",
]
}
Similarly, babel-polyfill should be #babel/polyfill.
None of this is well documented yet because Babel 7 is still an unstable beta.
I met the same challenge while configuring jest to work with babel-6.
See complete explanation here
But in summary, this combination of --devDependencies worked for me, and i set-up babel-jest to transform my **.js files:
// package.json
"devDependencies": {
"babel-core": "6.26.0",
"babel-jest": "21.2.0",
"babel-loader": "7.1.2",
"babel-preset-env": "1.6.0",
"babel-preset-react": "6.24.1",
"babel-preset-stage-0": "6.24.1",
"jest": "21.2.1",
"webpack": "3.6.0"
},
"jest": {
"transform": {
"^.+\\.jsx?$": "babel-jest"
}
}
// .babelrc
{
"presets": [
"env",
"stage-0",
"react"
]
}

Resources