create-react-app SyntaxError: Unexpected identifier when running a test - reactjs

I created my app with create-react-app and installed redux and everything is running as expected.
When creating the tests I ran into a few issues with one component that used open layers but corrected that issue with a command line when running the tests:
npm test -- --transformIgnorePatterns 'node_modules/(?!(ol)/)' --setupFiles 'jest-canvas-mock' jest --no-cache
The test that contains my reference to OpenLayers is now passing all is good there, but I have another component that uses Tab and Tabs from react-bootstrat/es/Tab and Tabs respectfully.
The simple test for that component is as follows:
import React from 'react';
import ReactDOM from 'react-dom';
import SideMenu from '../../side-menu/side-menu';
it ('should render without crashing', () => {
const div = document.createElement ('div');
ReactDOM.render (<SideMenu/>, div);
ReactDOM.unmountComponentAtNode(div);
});
When running the test command this is the only test that's failing in my project with the following error:
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import _extends from "#babel/runtime-corejs2/helpers/esm/extends";
^^^^^^^^
SyntaxError: Unexpected identifier
1 | import React, { Component } from 'react';
> 2 | import Tabs from "react-bootstrap/es/Tabs";
| ^
3 | import Tab from "react-bootstrap/es/Tab";
4 | import AvailableLayersMenu from '../available-layers-window/available-layers-menu-tree';
5 |
at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/script_transformer.js:403:17)
at Object.<anonymous> (src/side-menu/side-menu.js:2:1)
My .babelrc file is as follows:
{
"presets": [
"env",
"react",
["es2015", {"modules": true}],
"stage-1"
]
}
I'm not sure what's going on and have been at this for 2 full days with no progress on this last test. Any help would be much appreciated.

Well, after countless wasted hours my co-worker found the solution:
npm test -- --transformIgnorePatterns 'node_modules/(?!(ol|react-bootstrap|#babel)/)' --setupFiles 'jest-canvas-mock' jest --no-cache

Related

React + Jest Testing Error - ReferenceError: expect is not defined

I have literally trawled everywhere for an answer to this and possibly tried 99% of things out there so i decided to start a thread of its own so others can run their eyes over what i have currently and see if they can spot the issue.
i am very new to Jest testing and decided to try implement it onto our code base. i used this guide to make sure everything i done was perfect but still this error occurs
A Practical Guide To Testing React Applications With Jest
I am testing this aginst a simple functional component which uses react-hook-form to produce a form on the page and then sends the completed form to our backend via a redux call
I have setup the setupTests.js file as:
import '#testing-library/jest-dom'
import { configure } from "enzyme"
import Adapter from "enzyme-adapter-react-16";
import '#testing-library/jest-dom/extend-expect';
configure({ adapter: new Adapter() });
Updated my package.json test command to
"test": "react-scripts test --env=jsdom --setupFiles ./src/setupTests.js"
Here is the test spec im trying to run with a simple test:
import React from 'react';
import { render as rtlRender, screen } from '#testing-library/react';
import { Provider } from 'react-redux';
import store from '../../../store';
import AddNewProperty from './AddNewProperty';
configure({ adapter: new Adapter() });
const render = component => rtlRender(
<Provider store={store()}>
{component}
</Provider>
)
describe('Add New Property', () => {
test('component redners successfully', () => {
render(<AddNewProperty />)
// expect(screen.getByText('Apartment Number')).toBeInTheDocument();
})
});
here is the error returned on the screen for me:
FAIL src/components/Forms/Agency/AddNewProperty.spec.js
● Test suite failed to run
ReferenceError: expect is not defined
3 | import Adapter from "enzyme-adapter-react-16";
4 | import '#testing-library/jest-dom/extend-expect';
> 5 | configure({ adapter: new Adapter() });
| ^
at Object.<anonymous> (node_modules/#testing-library/jest-dom/dist/extend-expect.js:9:1)
at Object.<anonymous> (node_modules/#testing-library/jest-dom/dist/index.js:3:1)
at Object.<anonymous> (src/setupTests.js:5:1)
Test Suites: 1 failed, 1 total
Tests: 0 total
Snapshots: 0 total
Time: 0.167s
Ran all test suites related to changed files.
Watch Usage: Press w to show more.
I have all the packages installed in with the latest versions also
You would want to set up the files after the test framework has been installed
Here are a couple of ways you can go about doing it (For this particular question, method 1 is more relevant)
1) react-scripts
Replace/Add --setupFilesAfterEnv instead of using --setupFiles
Example: "test": "react-scripts test --setupFilesAfterEnv <test setup filepath>
2) jest.config.js
setupFilesAfterEnv: [
'./setupTests.js',
],
Along with that make sure your node version is at least 12

Does React.lazy() works with Create React App?

I have created one React App using npx create-react-app my-app cmd (React 17 version). Now
Well, I just tried to replace a classic
import Component from './Component'
to
const Component = React.lazy(() => import('./Component'));
and then
<React.Suspense fallback={<div>Loading.. </div>}>
<Component />
</React.Suspense>
but it throws error like
SyntaxError: Unexpected token at import(6:22)
> 6 | const Component = React.lazy(() => import('./Component'));
Can anyone help me to resolve this?
This is the code syntax
And this is the suspense component
And this is the compilation output
My package.json looks like
I'm not sure, if this fixes your issue, but maybe you can give it a try. Are you using Babel?
It says:
When using Babel, you’ll need to make sure that Babel can parse the
dynamic import syntax but is not transforming it. For that you will
need #babel/plugin-syntax-dynamic-import.
https://reactjs.org/docs/code-splitting.html#import
I've created a .babelrc file on the project root and added the content:
{
"plugins": [
"#babel/plugin-syntax-dynamic-import"
]
}
I also imported lazy in my component:
import React, { Component, lazy, useEffect, useState } from 'react';
In my project React.lazy is working fine this way.

Jest testing throws error because of gatsby webpack configuration

I added to my gatsby's webpack config directory-named-webpack-plugin which makes it possible to import files that have the same name as its parent direcory. For example I can use path 'components/Link' instead of 'components/Link/Link':
const DirectoryNamedWebpackPlugin = require('directory-named-webpack-plugin');
exports.onCreateWebpackConfig = ({ actions }) => {
actions.setWebpackConfig({
resolve: {
plugins: [new DirectoryNamedWebpackPlugin()],
},
});
};
But unfortunately when I run my test using jest I get an error like that (I also use absolute imports):
FAIL src/components/atoms/Link/Link.test.js
● Test suite failed to run
Cannot find module 'components/atoms/Icon' from 'src/components/atoms/Link/Link.js'
Require stack:
src/components/atoms/Link/Link.js
src/components/atoms/Link/Link.test.js
3 | import { useAnimation } from 'framer-motion';
4 | import PropTypes from 'prop-types';
> 5 | import Icon from 'components/atoms/Icon';
| ^
6 | import arrow from 'assets/svgs/icon_arrow.svg';
7 | import S from './Link.styles';
8 | import animations from './Link.animations';
at Resolver.resolveModule (node_modules/jest-resolve/build/index.js:307:11)
at Object.<anonymous> (src/components/atoms/Link/Link.js:5:1)
Here is my folder structure:
Is there any solution to this? I'm pretty new in the jest configuration.
Use index.js in each folders like this and forget DirectoryNamedWebpackPlugin at all
import Link from './Link';
export default Link;

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.

Jest testing error: Unexpected token <

Im trying to test my components with Jest.
I believe that I've installed all the required modules to run the tests.
Last thing that I did was to run
yarn add -D babel-plugin-transform-es2015-modules-commonjs.
This is my code while trying to do a simple Jest test:
import React, { Component } from 'react';
import { shallow } from 'enzyme';
import Market from '../src/components/Market.js';
test('Market should render as expected', () => {
const component = shallow(<Market />);
console.log(component);
});
The error message on the console points to the first < at the start of invoking the Market component on line 6.
I had the same issue. Adding transform or anything didn't fix it. So i finally added .babelrc file and added following configuration and it worked.
{
"presets": ["es2015", "react"]
}
Hope this will help you.

Resources