Jest says SyntaxError: Unexpected token export - React, Material.io - reactjs

I am using React, Google Material IO Components to build an app. From a while when I am running JEST for my tests I see this error mentioned below.
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:
C:\Users\sganesh\Documents\gateway-web\packages\payments\node_modules\#material\textfield\helper-text\index.js:23
export * from './component';
^^^^^^
SyntaxError: Unexpected token export
2 | import { useState, useEffect, useRef } from "react";
3 | import { MDCTextField } from "#material/textfield";
> 4 | import { MDCTextFieldHelperText } from "#material/textfield/helper-text";
| ^
5 | import { MDCChipSet } from "#material/chips";
6 | import { MDCFloatingLabel } from "#material/floating-label";
7 | import { MDCTextFieldCharacterCounter } from '#material/textfield/character-counter';
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/PaymentContainer/PaymentDetails/common/ChipInput/ChipInput.tsx:4:1)
The Jest Configuration is as follows:-
const base = require('../jest.config.base.js')
// Individual pod can add their add own custom jest config
module.exports = {
...base,
"setupFiles": ['<rootDir>/src/setupTests.ts'],
transformIgnorePatterns: [
"<rootDir>/node_modules/?!(#rmwc|#material)/"
]
};
The Base Jest Config is:
module.exports = {
roots: ["<rootDir>/src"],
transform: {
"^.+\\.(ts|tsx)$": "ts-jest",
".+\\.(css|scss)$": "<rootDir>/node_modules/jest-css-modules-transform"
},
moduleFileExtensions: [
"ts",
"tsx",
"js",
"tsx"
],
"snapshotSerializers": ["enzyme-to-json/serializer"],
verbose: true
};

Try without the <rootDir>
transformIgnorePatterns: [
'node_modules/?!(#rmwc|#material)/'
]

Related

How to fix ReferenceError: TextEncoder is not defined in jest test of Next.js project?

I have a unit test that is checking to see if a particular item is rendered on the page. This unit test fails and I get the following error:
Test suite failed to run
ReferenceError: TextEncoder is not defined
6 | import { unformatPhoneNumber } from '../../../utils/formatter';
7 | import ReactHtmlParser from 'react-html-parser';
> 8 | import DOMPurify from 'isomorphic-dompurify';
Based on the other stackoverflow questions on this subject, I added a jest.config.js file and a jest.setup.js file in the root of my project.
This is what I have in my jest.config.js, which I copied from the Next.js example repo here,
https://github.com/vercel/next.js/tree/canary/examples/with-jest-babel
// You can learn more about each option below in the Jest docs: https://jestjs.io/docs/configuration.
module.exports = {
collectCoverageFrom: ['**/*.{js,jsx,ts,tsx}', '!**/*.d.ts', '!**/node_modules/**'],
moduleNameMapper: {
// Handle CSS imports (with CSS modules)
// https://jestjs.io/docs/webpack#mocking-css-modules
'^.+\\.module\\.(css|sass|scss)$': 'identity-obj-proxy',
// Handle CSS imports (without CSS modules)
'^.+\\.(css|sass|scss)$': '<rootDir>/__mocks__/styleMock.js',
// Handle image imports
// https://jestjs.io/docs/webpack#handling-static-assets
'^.+\\.(png|jpg|jpeg|gif|webp|avif|ico|bmp|svg)$': `<rootDir>/__mocks__/fileMock.js`,
// Handle module aliases
'^#/components/(.*)$': '<rootDir>/components/$1',
'^#/pages/(.*)$': '<rootDir>/pages/$1',
},
setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],
testPathIgnorePatterns: ['<rootDir>/node_modules/', '<rootDir>/.next/'],
transform: {
// Use babel-jest to transpile tests with the next/babel preset
// https://jestjs.io/docs/configuration#transform-objectstring-pathtotransformer--pathtotransformer-object
'^.+\\.(js|jsx|ts|tsx)$': ['babel-jest', { presets: ['next/babel'] }],
},
transformIgnorePatterns: ['/node_modules/', '^.+\\.module\\.(css|sass|scss)$'],
testEnvironment: 'jest-environment-jsdom',
};
This is what I have in the jest.setup.js,
// Optional: configure or set up a testing framework before each test.
// If you delete this file, remove `setupFilesAfterEnv` from `jest.config.js`
// Used for __tests__/testing-library.js
// Learn more: https://github.com/testing-library/jest-dom
import '#testing-library/jest-dom/extend-expect';
import { TextEncoder, TextDecoder } from 'util';
global.TextEncoder = TextEncoder;
global.TextDecoder = TextDecoder;
After adding this, I am still getting the same error. I am using node v16.18.0.
This is a Nextjs, Typescript, React app. I also have a jest-config.d.ts file with the following in it:
declare const root: any;
export { root as rootDir };
export declare const setupFilesAfterEnv: string['<rootDir>/jest.setup.js'];
export declare const testMatch: string[];
export declare const testPathIgnorePatterns: string[];
export declare const coveragePathIgnorePatterns: string[];
export declare const coverageDirectory: string;
//# sourceMappingURL=jest-config.d.ts.map
I don't know if I need to add anything into this file.

Jest / React Testing Library, So Many Errors

I'm new to React Testing Library and Jest. I could successfully run a simple set of tests on it, like the below,
but when I tried to test on my "App.js", where a lot of imports/requires, it started to get a many set of errors on the each import, and I'm tbh overwhelmed.
Here's a working example:
./src/dev/test/AppTmp.js
import React from "react";
export const Topbar = () => {
return (
<>
<p>hoge.</p>
</>
)
}
./src/__tests__/hello.js
import '#testing-library/jest-dom/extend-expect'
import React from 'react'
import { render, screen } from '#testing-library/react'
import * as renderer from "react-test-renderer";
import { Topbar } from '../dev/test/AppTmp'
test('tmp test.', () => {
const component = renderer.create(
<Topbar />,
);
let tree = component.toJSON();
expect(tree).toMatchSnapshot();
})
The above successfully runs.
A problem is when I add an import line like this:
./src/dev/test/AppTmp.js
import React from "react";
import ReactMarkdown from 'react-markdown'; // <--- added this
export const Topbar = () => {
return (
<>
<p>hoge.</p>
</>
)
}
./src/__tests__/hello.js
import '#testing-library/jest-dom/extend-expect'
import React from 'react'
import { render, screen } from '#testing-library/react'
import * as renderer from "react-test-renderer";
import { Topbar } from '../dev/test/AppTmp'
test('tmp test.', () => {
const component = renderer.create(
<Topbar />,
);
let tree = component.toJSON();
expect(tree).toMatchSnapshot();
})
The above, with just an extra import line, causes the following error:
● 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.
...
...
Details:
/home/user/pg/react/myapp/node_modules/react-markdown/index.js:6
export {uriTransformer} from './lib/uri-transformer.js'
^^^^^^
SyntaxError: Unexpected token 'export'
24 | import "prismjs/themes/prism-tomorrow.css";
25 | import { LoremIpsum } from "react-lorem-ipsum";
> 26 | import ReactMarkdown from 'react-markdown';
| ^
27 |
28 | export const Topbar = () => {
29 | return (
at Runtime.createScriptFromCode (../node_modules/jest-runtime/build/index.js:1796:14)
at Object.<anonymous> (dev/test/AppTmp.js:26:1)
Test Suites: 1 failed, 2 passed, 3 total
(note: actually I had more lines as showing above, but what I'm doing is essentially the same, so kindly ignore them)
So this is an SyntaxError: Unexpected token 'export' error. Well, At first I thought I'm going to solve the error on SO or Google. But the error hell continues...
Now I added a different line as the following.
./src/dev/test/AppTmp.js
import React from "react";
// import ReactMarkdown from 'react-markdown';
import Slider from "react-slick"; // <--- added this
export const Topbar = () => {
return (
<>
<p>hoge.</p>
</>
)
}
The above caused an error:
● Test suite failed to run
matchMedia not present, legacy browsers require a polyfill
25 | import { LoremIpsum } from "react-lorem-ipsum";
26 | // import ReactMarkdown from 'react-markdown';
> 27 | import Slider from "react-slick";
| ^
28 | import "slick-carousel/slick/slick.css";
29 | import "slick-carousel/slick/slick-theme.css";
30 | import 'bootstrap';
at new MediaQueryDispatch (../node_modules/enquire.js/src/MediaQueryDispatch.js:15:15)
at Object.<anonymous> (../node_modules/enquire.js/src/index.js:2:18)
at Object.<anonymous> (../node_modules/react-slick/lib/slider.js:50:53)
at Object.<anonymous> (../node_modules/react-slick/lib/index.js:8:38)
at Object.<anonymous> (dev/test/AppTmp.js:27:1)
at Object.<anonymous> (__tests__/hello.js:8:1)
Test Suites: 1 failed, 2 passed, 3 total
This time I got an matchMedia not present, legacy browsers require a polyfill error.
Error hell continues. Next I tried:
./src/dev/test/AppTmp.js
import React from "react";
// import ReactMarkdown from 'react-markdown';
// import Slider from "react-slick";
import { nanoid } from 'nanoid'; // <--- added this
export const Topbar = () => {
return (
<>
<p>hoge.</p>
</>
)
}
● 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.
...
...
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:
/home/user/pg/react/myapp/node_modules/nanoid/index.browser.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){import { urlAlphabet } from './url-alphabet/index.js'
^^^^^^
SyntaxError: Cannot use import statement outside a module
49 | // import uniqueId from 'lodash/utility/uniqueId'
50 | import _ from 'lodash'
> 51 | import { nanoid } from 'nanoid';
| ^
52 | import { WithContext as ReactTags } from 'react-tag-input';
53 |
54 | const mymodules = require("./../../mymodules.js")
at Runtime.createScriptFromCode (../node_modules/jest-runtime/build/index.js:1796:14)
at Object.<anonymous> (dev/test/AppTmp.js:51:1)
Test Suites: 1 failed, 2 passed, 3 total
This time, got an error SyntaxError: Cannot use import statement outside a module. What the hell is going on.....
./.babelrc
{
"presets": [
[
"#babel/preset-env",
{
"loose": true,
"modules": false,
"targets": {
"browsers": "last 2 chrome versions"
}
}
],
"#babel/preset-react"
],
"plugins": [
"react-hot-loader/babel",
["#babel/plugin-proposal-class-properties", { "loose": true }]
],
"env": {
"test": {
"presets": [
[
"#babel/preset-env",
{
"loose": true,
"modules": false
}
],
"#babel/preset-react"
],
"plugins": [
"#babel/plugin-transform-runtime",
"#babel/plugin-transform-modules-commonjs"
]
}
}
}
./package.json
"jest": {
"moduleNameMapper": {
"\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/__mocks__/fileMock.js",
"\\.(css|less|scss)$": "<rootDir>/__mocks__/styleMock.js"
},
"transform": {
"\\.[jt]sx?$": "babel-jest"
},
"moduleFileExtensions": [
"js",
"jsx",
"tsx"
],
"moduleDirectories": [
"node_modules"
],
"rootDir": "src",
"transformIgnorePatterns": [
"/node_modules/(?![#autofiy/autofiyable|#autofiy/property]).+\\.js$",
"/node_modules/(?![#autofiy/autofiyable|#autofiy/property]).+\\.ts$",
"/node_modules/(?![#autofiy/autofiyable|#autofiy/property]).+\\.tsx$",
"/node_modules/(?!my-package)(.*)",
"/node_modules/(?!#ngrx|(?!deck.gl)|ng-dynamic)"
],
"testEnvironment": "jsdom"
},
So, what's the best thing I can do now?
actually I've been taking 8 hours so far on Jest to get the above-mentioned simple example working, I didn't expect just a testing development environment building is this damn hard way.
I mean I think I'm doing something fundamentally wrong. that's why I'm getting this many errors no? What's not right with this setup, can I ask a help? Thanks.

How to import SVG in ReactJS with craco?

I'm struggling to import SVG's when I'm using craco in my react app.
It's suggested to use #svgr/webpack but I'm not sure how to put it into my craco.config.js
My current setup as per this (I prob shouldn't follow someone's config that doesn't work and expect it to work tho) that does not work:
// craco.config.js
const CracoAlias = require("craco-alias");
module.exports = {
plugins: [
{
plugin: CracoAlias,
options: {
source: "tsconfig",
baseUrl: "./src",
tsConfigPath: "./tsconfig.paths.json"
}
},
],
webpack: {
configure: (config, { env, paths }) => {
config.module.rules.push({
test: /\.svg$/,
use: ["#svgr/webpack"]
});
return config;
}
}
};
The craco.config.js webpack documentation is here but it's so confusing to me without concrete examples.
Also to note:
Writing import {ReactComponent as mySvg} from "./mySvg.svg" doesn't work because it doesn't recognize it as a ReactComponent.
If I try importing directly via import mySvg from "./mySvg.svg" Typescript doesn't recognize the file.
What I'm currently doing is putting the svg into a React component and using that but it's a nightmare doing that every time. I also put this in #types/custom.d.ts, but it still doesn't work when put into <img src={mySvg} />
// #types/custom.d.ts
declare module "*.svg" {
const content: any;
export default content;
}
import {reactComponent as GoogleLogo} from "../assets/image/googlelogo.svg;
GoogleLogo is component and reactComponent is a required magic string
i find the fix your problem in Adding svgr to create-react-app via craco

ECMAScript module error when running react-scripts test

I am having trouble getting my test runner to run properly within my React/Typescript application. When I try and run it, I get the following error:
Watch Usage
› Press a to run all tests.
FAIL src/components/InvestmentStyleSlider/index.test.tsx
● 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:
• If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/en/ecmascript-modules for how to enable it.
• 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:
D:\projects\cult-wines-repos\CultWines.Onboarding.Ui\node_modules\react-bootstrap\esm\Button.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import _extends from "#babel/runtime/helpers/esm/extends";
^^^^^^
SyntaxError: Cannot use import statement outside a module
1 | import React from 'react';
FAIL src/components/InvestmentStyleSlider/index.test.tsx
I am a tad confused as I have another application that is built in the same way and this has no issues whatsoever.I have tried amending the jest config to the following in my package.json but no matter what I do it still spits out the same error
"version": "0.1.0",
"private": true,
"jest": {
"testEnvironment": "jest-environment-node",
"transform": {}
},
"dependencies": {
Has anyone had a similar error before or can advise as to what is happening here? Again, I am using the react-scripts version of jest which I presumed has ecmascript module support out of the box.
Here is my setupTest.js file in case that gives further clues:
import '#testing-library/jest-dom/extend-expect';
import 'jest-styled-components';
import { configure } from 'enzyme';
import Adapter from '#wojtekmaj/enzyme-adapter-react-17';
import { createSerializer } from 'enzyme-to-json';
configure({ adapter: new Adapter() });
expect.addSnapshotSerializer(createSerializer({ mode: 'deep' }));
And the very simple test file that fails:
/* eslint-disable #typescript-eslint/no-unused-vars */
import React from 'react';
import { render } from 'enzyme';
import InvestmentStyleSlider from './index';
describe('Investment Style Slider', () => {
it('renders correctly', () => {
const rendering = render(<InvestmentStyleSlider />);
expect(rendering).toMatchSnapshot();
});
});
Thanks

SyntaxError: Unexpected token import with Jest

I'm trying to setup a jest snapshot test with redux-persist in my react-native project. I don't think its an es2015 imports problem as my test code looks something like this:
import React from "react"
import "react-native"
// Note: test renderer must be required after react-native.
import renderer from "react-test-renderer"
import App from "../App"
it("renders correctly", () => {
const app = renderer.create(<App />).toJSON()
expect(app).toMatchSnapshot()
})
I ran this exact same test before I added redux-persist and it was working.
Error thrown by jest:
● Test suite failed to run
/Users/a_050313/Documents/dev/scheduling/node_modules/redux-persist/es/integration/react.js:9
import React, { PureComponent } from 'react'; // eslint-disable-line import/no-unresolved
^^^^^^
SyntaxError: Unexpected token import
1 | import React, { Component } from "react"
2 | import { Provider } from "react-redux"
> 3 | import { PersistGate } from "redux-persist/es/integration/react"
4 |
5 | import "./__debug__/ReactotronConfig" // Run Reactron Tools config
6 |
at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/script_transformer.js:318:17)
at Object.<anonymous> (App.js:3:13)
at Object.<anonymous> (__tests__/App.js:7:10)`
The error was related to es2015 imports but It is on jest end. By default jest only transpiles project code and react-native code. So the added libs which aren't already transpilled would error out by jest.
(as mentioned on jest docs)
By default the jest-react-native preset only processes the project's own source files and react-native
Solution provided on the official docs seems a bit hacky but thats the only thing I found:
Add following in your package.json jest: { } section or in jest.config.js file.
"transformIgnorePatterns": [
"node_modules/(?!(react-native|my-project|redux-persist)/)"
]
where the bit redux-persist is the thing that solves the problem. If you have problem with other libs just add their names. My list looks something like this:
"jest": {
"preset": "react-native",
"transformIgnorePatterns": [
"node_modules/(?!(react-native|my-project|redux-persist|react-native-linear-gradient|react-native-vector-icons|react-navigation)/)"
]
}
Additional Note just for redux-persist if you import PersistGate from
import { PersistGate } from "redux-persist/lib/integration/react"
instead
import { PersistGate } from "redux-persist/es/integration/react"
(reference)
you'll get the compiled version but for other libs still you got to this the above mentioned solution.

Resources