Jest encountered an unexpected token - reactjs

I have just started learning react testing library with jest and created a sample application to mock the server.my node version is v16.13.0. However, I am getting following error "SyntaxError: Cannot use import statement outside a module". I even write import axios from './lib/axios' but I got the same error.
Jest encountered an unexpected token
Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.
Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration.
By default "node_modules" folder is ignored by transformers.
Here's what you can do:
• If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/ecmascript-modules for how to enable it.
• If you are trying to use TypeScript, see https://jestjs.io/docs/getting-started#using-typescript
• 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/configuration
For information about custom transformations, see:
https://jestjs.io/docs/code-transformation
Details:
D:\test-projects\icecream\node_modules\axios\index.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){import axios from './lib/axios.js';
^^^^^^
SyntaxError: Cannot use import statement outside a module
> 1 | import axios from "axios";
| ^
2 | import { useEffect, useState } from "react";
3 | import { Row } from "react-bootstrap";
4 | import ScoopOption from "./ScoopOptions";
at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1728:14)
at Object.<anonymous> (src/pages/entry/Options.jsx:1:1)
my test
import Options from "../Options";
import { render, screen } from "#testing-library/jest-dom";
test("displays image for each scoop option from the server",async () => {
render(<Options optionType="scoop" />);
const scoopImages = await screen.findAllByRole("img", { name: /scoop$/i });
expect(scoopImages).toHaveLength(2);
});
this is some of my code (Options.jsx):
import axios from "axios";
const [items, setItems] = useState([]);
useEffect(() => {
axios
.get(`http://localhost:3030/${optionType}`)
.then((response) => setItems(response.data))
.catch((err) => {});
}, [optionType]);
my package.json is:
{
"name": "icecream",
"version": "0.1.0",
"private": true,
"type": "module",
"dependencies": {
"#babel/plugin-transform-modules-commonjs": "^7.20.11",
"#testing-library/jest-dom": "^5.16.5",
"#testing-library/react": "^13.4.0",
"axios": "^1.2.1",
"bootstrap": "^5.2.3",
"eslint-plugin-jest-dom": "^4.0.3",
"eslint-plugin-testing-library": "^5.9.1",
"msw": "^0.49.2",
"react": "^18.2.0",
"react-bootstrap": "^2.7.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"devDependencies": {
"#babel/core": "^7.20.7",
"#babel/preset-env": "^7.20.2",
"#testing-library/user-event": "^14.4.3",
"babel-jest": "^29.3.1"
}
}

this error occurs in axios in 1.x.x version and it is because of the change of transpilers from babel to Common js.
I solved this problem by changing "test" in my package.json to:
"test": "react-scripts test --transformIgnorePatterns \"node_modules/(?!axios)/\"",

Related

How to connect mongoDB in react

Such a problem that when I try to simply connect mongoDB in react
import React, {Component} from 'react';
export default class App extends Component{
componentDidMount(){
const {MongoClient} = require('mongodb');
const client = new MongoClient('mongodb+srv://dafu4k:****#cluster0.jd26aac.mongodb.net/?retryWrites=true&w=majority');
const start = async () => {
try{
await client.connect();
console.log('Connected')
}
catch(e){
console.log(e)
}
}
start();
}
render(){
return (
<>
<h1>Home page</h1>
</>
)
}
}
Errors of the same type appear in the browser itself
Module not found: Error: Can't resolve 'os' in 'C:\Users\DaFu4\OneDrive\Рабочий >стол\mongotest\mongo-test\node_modules\ip\lib'
BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.
If you want to include a polyfill, you need to:
add a fallback 'resolve.fallback: { "os": require.resolve("os-browserify/browser") }'
install 'os-browserify'
If you don't want to include a polyfill, you can use an empty module like this:
resolve.fallback: { "os": false }
They differ in that the last line has different keys (timers,crypto,http, etc.)
I watched how to connect mongoDB to react, everywhere they used a certain mongoose along with mongoDB, but I can’t understand, maybe it’s required to connect to react, or am I still doing something wrong? (in normal js everything works fine, the code has not changed)
src/index.js
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
package.json
{
"name": "mongo-test",
"version": "0.1.0",
"private": true,
"dependencies": {
"#testing-library/jest-dom": "^5.16.4",
"#testing-library/react": "^13.3.0",
"#testing-library/user-event": "^13.5.0",
"crypto-browserify": "^3.12.0",
"mongodb": "^4.7.0",
"react": "^18.1.0",
"react-dom": "^18.1.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
We can not connect React JS to MongoDB because things don’t work like this.
First, we create a react app, and then for backend maintenance, we create API in node.js and express.js which is running at a different port and our react app running at a different port. for connecting React to the database (MongoDB) we integrate through API.
Check this link:
[1]: https://www.geeksforgeeks.org/how-to-connect-mongodb-with-reactjs/#:~:text=First%2C%20we%20create%20a%20react,MongoDB)%20we%20integrate%20through%20API.
React is not communicating directly with MONGODB (via mongoose). It interacts with nodejs/express which is the one to communicate with MONGODB.
The explanation for the steps are presented in what I find to be the clearest form, in MERN STACK TUTORIAL (MERN = Mongodb, Express, React and Nodejs),
especially as the most essential part doesn't exist in Geeks4Geeks' tutorial (the part where they show you an example code of index.html).
Good luck!

Jest and Enzyme configuration is not properly working my React/Typescript Project

Some thing went wrong when I start npm test.
Here is my package.json:
{
"name": "my-app",
"version": "0.1.0",
"private": true,
"dependencies": {
"#testing-library/jest-dom": "^5.11.8",
"#testing-library/react": "^11.2.2",
"#testing-library/user-event": "^12.6.0",
"#types/enzyme": "^3.10.8",
"#types/jest": "^26.0.19",
"#types/node": "^12.19.12",
"#types/react": "^16.14.2",
"#types/react-dom": "^16.9.10",
"node-sass": "^4.14.1",
"react": "^17.0.1",
"react-dom": "^17.0.1",
"react-scripts": "4.0.1",
"ts-jest": "^26.4.4",
"typescript": "^4.1.3",
"web-vitals": "^0.2.4"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"devDependencies": {
"#types/enzyme-adapter-react-16": "^1.0.6",
"enzyme": "^3.11.0",
"enzyme-to-json": "^3.6.1",
"jest-enzyme": "^7.1.2"
},
"jest": {
"setupTestFrameworkScriptFile": "<rootDir>/path/to/setupTest.js"
}
}
Here is my-app/jest.config.js
// For a detailed explanation regarding each configuration property, visit:
// https://jestjs.io/docs/en/configuration.html
module.exports = {
// Automatically clear mock calls and instances between every test
clearMocks: true,
// An array of glob patterns indicating a set of files for which coverage information should be collected
collectCoverageFrom: ["src/**/*.{js,jsx,mjs}"],
// The directory where Jest should output its coverage files
coverageDirectory: "coverage",
// An array of file extensions your modules use
moduleFileExtensions: ["js", "json", "jsx"],
// The paths to modules that run some code to configure or set up the testing environment before each test
setupFiles: ["<rootDir>/enzyme.config.js"],
// The test environment that will be used for testing
testEnvironment: "jsdom",
// The glob patterns Jest uses to detect test files
testMatch: ["**/__tests__/**/*.js?(x)", "**/?(*.)+(spec|test).js?(x)"],
// An array of regexp pattern strings that are matched against all test paths, matched tests are skipped
testPathIgnorePatterns: ["\\\\node_modules\\\\"],
// This option sets the URL for the jsdom environment. It is reflected in properties such as location.href
testURL: "http://localhost",
// An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation
transformIgnorePatterns: ["<rootDir>/node_modules/"],
// Indicates whether each individual test should be reported during the run
verbose: false,
};
here is my-app/setupTests.ts
/** Used in jest.config.js */
import { configure } from "enzyme";
import Adapter from "enzyme-adapter-react-16";
configure({ adapter: new Adapter() });
here is my test case Header.unit.test.tsx
import * as React from "react";
import { shallow } from "enzyme";
import Header from "./Header";
describe("Header Component", () => {
it("It should be render without errors", () => {
const component = shallow(<Header />);
console.log(component.debug);
const wrapper = component.find(".headerComponent");
expect(wrapper.length).toBe(1);
});
});
And here is the error that I am encountering, when running the test:
Enzyme Internal Error: Enzyme expects an adapter to be configured, but found none.
To configure an adapter, you should call `Enzyme.configure({ adapter: new Adapter() })`
before using any of Enzyme's top level APIs, where `Adapter` is the adapter
corresponding to the library currently being tested. For example:

Jest encountered an unexpected token when I run the npm run test

Good day. I create a app using react and add the library of #testing-library/react. I also install use-global-hook and I was having an error when I run the npm run test. anyone could help me to get out to this error. Thanks
here's my pakage.json.
[package.json][1]
{
"name": "trial",
"version": "0.1.0",
"private": true,
"dependencies": {
"#babel/core": "^7.9.6",
"#testing-library/jest-dom": "^4.2.4",
"#testing-library/user-event": "^7.1.2",
"react": "^16.13.1",
"react-dom": "^16.13.1",
"react-router-dom": "^5.1.2",
"react-scripts": "3.4.1",
"use-global-hook": "^0.1.12"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"ie 11",
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"devDependencies": {
"#babel/plugin-transform-modules-commonjs": "^7.9.6",
"#testing-library/react": "^9.5.0",
"react-test-renderer": "^16.13.1"
}
}
here's the error details
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".
Details:
E:\Backups\Projects\React\trial\node_modules\use-global-hook\index.js:60
export default useStore;
^^^^^^
SyntaxError: Unexpected token 'export'
1 | import React from 'react';
> 2 | import globalHook from 'use-global-hook';
| ^
3 | import actions from './actions';
4 | import initState from './initState';
5 |
at ScriptTransformer._transformAndBuildScript (node_modules/#jest/transform/build/ScriptTransformer.js:537:17)
at ScriptTransformer.transform (node_modules/#jest/transform/build/ScriptTransformer.js:579:25)
at Object.<anonymous> (src/services/useGLobal.js:2:1)
I checked the use-global-hook repo. It seems that this package is distributed in ES Module. You will need to set up transformer for Jest so it understands ES module syntax.
This is the documentation for Jest transform config

jest encountered an unexpected token-looks like not able to transform jsx elements

I have originally started with react-scripts test but Console.log is not behaving properly(it print messages sometimes) so i decided to move on to jest (console.log works with jest,also jest can support more than react-script test).
Now,I am getting below error.
FAIL src/App.test.js
● Test suite failed to run
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
App.test.js: Unexpected token (11:20)
it('renders without crashing', () => {
const div = document.createElement('div');
ReactDOM.render(<App />, div);
^
ReactDOM.unmountComponentAtNode(div);
});
Environment
this application is on windows 10 pro
node v10.9.0
npm 6.2.0
I have followed Does Jest support ES6 import/export?
but it throws same error,what is stage 0 and why stage 0 is dangerous?
package.json file
enter code here
{
"name": "my-ui",
"version": "0.1.0",
"private": true,
"dependencies": {
"node-sass": "^4.12.0",
"react": "^16.8.6",
"react-dom": "^16.8.6",
"react-router-dom": "^4.3.1",
"react-scripts": "^2.1.8"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"build-dev": "dotenv -e .env.development 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-jest": "^24.8.0",
"babel-preset-env": "^1.7.0",
"babel-preset-react": "^6.24.1",
"dotenv-cli": "^1.4.0",
"jest": "^24.8.0",
"jsx-to-string": "^1.4.0",
"react-test-renderer": "^16.8.6"
},
".babelrc": {
"presets": [
"es2015",
"react"
]
}
}
I have two test case- for this
one of them is showing me expected behavious and other is throwing above error.
I have App.test.js file
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
//below test case throws above error.
it('renders without crashing', () => {
const div = document.createElement('div');
ReactDOM.render(<App />, div);
ReactDOM.unmountComponentAtNode(div);
});
//below should print output - working correctly.
it('it is printing', () => {
console.log('Hellllooo');
expect(true).toBe(true);
});

Jest error with not transpiled node module

When trying to run a test Jest throws the encountered unexpected token error. I'm using ky http, which obviously causes the problem and not get's transpiled.
Test suite failed to run
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:
Z:\sepview.web\sepview-react\node_modules\ky\index.js:277
export default createInstance();
^^^^^^
SyntaxError: Unexpected token export
1 | import * as React from 'react';
> 2 | import ky from 'ky';
| ^
3 |
4 | class HttpService extends React.Component {
5 |
at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/script_transformer.js:403:17)
at Object.<anonymous> (src/components/HttpService.tsx:2:1)
Test Suites: 1 failed, 1 total
Here's my package.json
{
"name": "test",
"version": "0.1.0",
"private": true,
"dependencies": {
"#fortawesome/fontawesome-svg-core": "^1.2.7",
"#fortawesome/free-solid-svg-icons": "^5.4.2",
"#fortawesome/react-fontawesome": "^0.1.3",
"#types/d3": "^5.0.1",
"bootstrap": "^4.1.3",
"bootswatch": "^4.1.3",
"d3": "^5.7.0",
"d3-array": "^2.0.2",
"jquery": "^3.3.1",
"ky": "^0.5.1",
"moment": "^2.22.2",
"node-sass": "^4.9.4",
"popper.js": "^1.14.4",
"react": "^16.6.0",
"react-dom": "^16.6.0",
"react-router": "^4.3.1",
"react-router-dom": "^4.3.1",
"react-scripts": "2.1.1",
"typescript": "^3.1.6"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": [
">0.2%",
"not dead",
"not ie <= 11",
"not op_mini all"
],
"devDependencies": {
"#types/enzyme": "^3.1.14",
"#types/enzyme-adapter-react-16": "^1.0.3",
"#types/jest": "^23.3.9",
"#types/node": "^10.12.2",
"#types/react": "^16.4.18",
"#types/react-dom": "^16.0.9",
"#types/react-router": "^4.4.0",
"#types/react-router-dom": "^4.3.1",
"enzyme": "^3.7.0",
"enzyme-adapter-react-16": "^1.6.0"
},
"proxy": "http://localhost:43947"
}
When adding transform or transformIgnorePatterns to package.json like this:
"jest": {
"transform": {
"^.+\\.js$": "babel-jest"
},
"transformIgnorePatterns": [
"/node_modules/(?!(#ky)/).*/"
]
},
I get this error:
Out of the box, Create React App only supports overriding these Jest options:
• collectCoverageFrom
• coverageReporters
• coverageThreshold
• globalSetup
• globalTeardown
• resetMocks
• resetModules
• snapshotSerializers
• watchPathIgnorePatterns.
These options in your package.json Jest configuration are not currently supported by Create React App:
• transform
• transformIgnorePatterns
If you wish to override other Jest options, you need to eject from the default setup. You can do so by running npm run eject but remember that this is a one-way operation. You may also file an issue with Create React App to discuss supporting more options out of the box.
I also have a babel.config.js which is empty atm:
module.exports = function () {
const presets = [];
const plugins = [];
return {
presets,
plugins
};
}
Ejecting is not an option. I tryed solving this for + one week. Any help is heavily appreciated.
I had a similar problem using material-ui-next-pickers which was using es6 imports in dist/
This is because material-ui-next-pickers isn’t being transpiled before running in Jest. create-react-app excludes everything from ./node_modules.
We could fix this by changing transformIgnorePatterns but it isn't supported by create-react-app as noted in the question.
However, we can still pass it as command arg to react-script test --transformIgnorePatterns \"node_modules/(?!my-module)/\"
Example
"scripts": {
"test": "react-scripts test --transformIgnorePatterns \"node_modules/(?!material-ui-next-pickers)/\" --env=jsdom",
...
}
add
moduleNameMapper: {
'^ky$': require.resolve('ky').replace('index.js', 'umd.js'),
},
to your jest.config.js

Resources