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
Related
When trying to run jest under create-react-app v5 / react v18, jest is failing to use axios with following error:
FAIL src/App.test.tsx
● Test suite failed to run
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:
/Users/ducin/itcorpo-react-app/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 { API_URL, MAX_PAGE_SIZE } from './config';
3 | import { Employee } from '../typings';
4 | import { range } from '../utils';
at Runtime.createScriptFromCode (node_modules/react-scripts/node_modules/jest-runtime/build/index.js:1728:14)
at Object.<anonymous> (src/api/EmployeeApi.ts:1:1)
I have tried:
setting transformIgnorePattern: "test": "react-scripts test --transformIgnorePatterns \"node_modules/(?!axios)/\"",
setting custom env: "test": "react-scripts test --env=<rootDir>/custom-test-env.js",
ts-jest
custom babel config:
module.exports = {
presets: [
['#babel/preset-env', {targets: {node: 'current'}}],
'#babel/preset-typescript',
],
};
but none of the above worked...
my package.json:
{
"name": "react-app",
"private": true,
"dependencies": {
"#babel/preset-typescript": "^7.18.6",
"#testing-library/jest-dom": "^5.16.5",
"#testing-library/react": "^13.4.0",
"#testing-library/user-event": "^13.5.0",
"#types/classnames": "^2.3.1",
"#types/jest": "^27.5.2",
"#types/jest-axe": "^3.5.5",
"#types/node": "^16.18.11",
"#types/react": "^18.0.27",
"#types/react-dom": "^18.0.10",
"#types/react-redux": "^7.1.25",
"#types/react-router-dom": "^5.3.2",
"#types/uuid": "^9.0.0",
"axios": "^1.3.0",
"classnames": "^2.3.2",
"currency.js": "^2.0.4",
"immer": "^9.0.19",
"jest-axe": "^7.0.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-loader-spinner": "^5.3.4",
"react-redux": "^8.0.5",
"react-router-dom": "^5.3.0",
"react-scripts": "5.0.1",
"redux": "^4.2.1",
"redux-devtools-extension": "^2.13.9",
"redux-observable": "^2.0.0",
"redux-saga": "^1.2.2",
"redux-thunk": "^2.4.2",
"rxjs": "^7.8.0",
"styled-components": "^5.3.6",
"typescript": "4.9.4",
"uuid": "^9.0.0",
"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"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
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)/\"",
I am trying to add code coverage to cypress following this tutorial
I added #cypress/code-coverage and babel-plugin-istanbul to my package.json file below
{
"name": "quiz",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"cypress": "cypress open"
},
"dependencies": {
"next": "12.0.10",
"react": "17.0.2",
"react-dom": "17.0.2",
"sass": "^1.49.7"
},
"devDependencies": {
"#cypress/code-coverage": "^3.9.12",
"#types/node": "17.0.15",
"#types/react": "17.0.39",
"babel-plugin-istanbul": "^6.1.1",
"cypress": "^9.4.1",
"eslint": "8.8.0",
"eslint-config-next": "12.0.10",
"typescript": "4.5.5"
}
}
I configured my cypress/support/index.js
// Import commands.js using ES2015 syntax:
import './commands'
// Alternatively you can use CommonJS syntax:
// require('./commands')
import '#cypress/code-coverage/support'
I configured my cypress/plugins/index.js
/**
* #type {Cypress.PluginConfig}
*/
// eslint-disable-next-line no-unused-vars
module.exports = (on, config) => {
require('#cypress/code-coverage/task')(on, config)
on('file:preprocessor', require('#cypress/code-coverage/use-babelrc'))
return config
}
My .babelrc
{
"presets": [
"next/babel"
],
"plugins": [
"istanbul"
]
}
After I run my test I get the following message
Only found unit test code coverage. [#cypress/code-coverage]
After I run my quiz.spec.js test, I run
npx nyc report --reporter=text-summary
And get an empty coverage summary
What am I doing wrong?
My github
I think it was just a node_modules problem, as your repo worked after download and initialization. I think babel can fail silently if it's dependencies are out of order.
I removed package.lock (because I use yarn to manage things) and then yarn to init the dependecies.
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);
});
I am now using React Jest to test code. If a component is single, and not importing anything else, "npm test" runs smoothly. Now I want to test multiple components together, and I immediately get this error:
SyntaxError: Unexpected token .
It seemed whenever React is importing something else, such as this one:
require( './style/fixed-data-table.css' );
require( './style/jnpr-datatable.scss' );
and then using Jest, it is throwing the unexpected token "." error.
There must be something wrong in my settings, but where? My package.json file contains:
"jest": {
"unmockedModulePathPatterns": [
"<rootDir>/node_modules/react/",
"<rootDir>/node_modules/react-dom/",
"<rootDir>/node_modules/react-addons-test-utils/"
]
}
And the .babelrc file is already in the root. Also babel-jest is included.
Have a look at the Jest documentation for Webpack integration. The problem is that Jest can’t work with other stuff than JavaScript. So you have to mock all non-JavaScript files you import. The easiest way is to configure a moduleNameMapper in your Jest configuration.
{
"jest": {
"moduleNameMapper": {
"\\.(css|scss)$": "<rootDir>/__mocks__/styleMock.js"
}
}
}
With a __mocks__/styleMock.js, that looks like this.
module.exports = {};
The easiest is to add an identity-obj-proxy package:
yarn add --dev identity-obj-proxy
And use it to automatically mock CSS/SCSS modules.
Add this to the package.json:
"jest": {
"moduleNameMapper": {
"\\.(css|scss)$": "identity-obj-proxy"
}
}
Or the following to jest.config.ts:
moduleNameMapper: {
'\\.(css|scss)$': 'identity-obj-proxy'
}
This way (S)CSS module class names will be automatically retrieved in tests.
Here is the source.
npm i -D identity-obj-proxy
Add the below to file jest.config.js
moduleNameMapper: {
"\\.(css|less|scss|sass)$": "identity-obj-proxy"
}
File jest.config.js:
testEnvironment: 'jsdom',
The way I got away with this was by adding these two lines to my .babelrc file:
{
"presets": ["env", "react"],
"plugins": ["transform-class-properties"]
}
And my package.json file looks like this:
{
"name": "crud-redux",
"version": "0.1.0",
"private": true,
"dependencies": {
"react": "^16.4.0",
"react-dom": "^16.4.0",
"react-scripts": "1.1.4"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "NODE_ENV=test jest",
"eject": "react-scripts eject"
},
"devDependencies": {
"babel-jest": "^18.0.0",
"babel-loader": "^6.4.1",
"babel-plugin-transform-decorators-legacy": "^1.3.5",
"enzyme": "^2.9.1",
"jest": "^23.1.0",
"react-addons-test-utils": "^15.6.2",
"react-test-renderer": "^15.6.2",
"redux-mock-store": "^1.5.1",
"webpack": "^1.15.0",
"webpack-dev-server": "^1.16.5"
}
}