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.
Related
I am creating some snapshot testing with jest. It gives me error with SwiperJs.
In my test i just want to have snapshot that renders component. I also have a single feature component which renders a feature comes from static data. Its test is passing without problem.
When i run test it gives me that eror.
SyntaxError: Unexpected token 'export'
> 2 | import { Swiper, SwiperSlide } from 'swiper/react';
Features.jsx
import { Link } from 'react-router-dom';
import { Swiper, SwiperSlide } from 'swiper/react';
import { Pagination } from 'swiper';
import featuresData from '../../data/featuresData';
import Feature from './Feature';
import illustration from '../../assets/features-illustration.svg';
import star from '../../assets/star.svg';
const Features = () => {
return (
////rest of the component
<Swiper
pagination={{
clickable: true,
}}
modules={[Pagination]}
>
///rest of the swiper
)
}
Features.test.jsx:
import renderer from 'react-test-renderer';
import Features from '../Features';
describe('Features', () => {
it('renders correctly', () => {
const tree = renderer.create(<Features />).toJSON();
expect(tree).toMatchSnapshot();
});
});
I installed jest packages with :
yarn add --dev jest babel-jest #babel/preset-env #babel/preset-react react-test-renderer
The solution for me was to introduce the following into my jest configuration file:
module.exports = {
// ...
transformIgnorePatterns: ['node_modules/(?!(swiper|ssr-window))']
}
Depending on your setup this may differ. In my case I'm extending a config provided by a framework, so all we needed was the above, however see here for a more detailed configuration.
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.
The error comes out when I added Contact Form by using 'EmailJS'.
I can see the dependencies on Package.json look fine, but it says not defined.
"react": "^17.0.2",
"react-dom": "^17.0.2",
I changed the importing format as following as advised,
import React from 'react';
import ReactDOM from 'react-dom';
also re-installed it, But, still the error is not fixed.
ReferenceError: React is not defined
at Object.children (C:\Users\Han\Desktop\andamilo\24-shopifystorehelp\.next\server\pages\index.js:3460:62)
at BaseAccordion.render (C:\Users\Han\Desktop\andamilo\24-shopifystorehelp\.next\server\pages\index.js:3595:23)
at processChild (C:\Users\Han\Desktop\andamilo\24-shopifystorehelp\node_modules\react-dom\cjs\react-dom-server.node.development.js:3450:18)
at resolve (C:\Users\Han\Desktop\andamilo\24-shopifystorehelp\node_modules\react-dom\cjs\react-dom-server.node.development.js:3270:5)
at ReactDOMServerRenderer.render (C:\Users\Han\Desktop\andamilo\24-shopifystorehelp\node_modules\react-dom\cjs\react-dom-server.node.development.js:3753:22)
at ReactDOMServerRenderer.read (C:\Users\Han\Desktop\andamilo\24-shopifystorehelp\node_modules\react-dom\cjs\react-dom-server.node.development.js:3690:29)
at renderToString (C:\Users\Han\Desktop\andamilo\24-shopifystorehelp\node_modules\react-dom\cjs\react-dom-server.node.development.js:4298:27)
at Object.renderPage (C:\Users\Han\Desktop\andamilo\24-shopifystorehelp\node_modules\next\dist\next-server\server\render.js:54:854)
at Function.getInitialProps (C:\Users\Han\Desktop\andamilo\24-shopifystorehelp\.next\server\pages\_document.js:791:19)
at Function.getInitialProps (C:\Users\Han\Desktop\andamilo\24-shopifystorehelp\.next\server\pages\_document.js:1373:85)
at loadGetInitialProps (C:\Users\Han\Desktop\andamilo\24-shopifystorehelp\node_modules\next\dist\next-server\lib\utils.js:5:101)
at renderToHTML (C:\Users\Han\Desktop\andamilo\24-shopifystorehelp\node_modules\next\dist\next-server\server\render.js:54:1145)
at runMicrotasks (<anonymous>)
at processTicksAndRejections (internal/process/task_queues.js:95:5)
at async C:\Users\Han\Desktop\andamilo\24-shopifystorehelp\node_modules\next\dist\next-server\server\next-server.js:112:97
at async C:\Users\Han\Desktop\andamilo\24-shopifystorehelp\node_modules\next\dist\next-server\server\next-server.js:105:142
anyone can advise what I am missing here?
first check if you are using babel and react 17. Add "runtime" : "automatic" to the config.
{
"presets": ["#babel/preset-env", ["#babel/preset-react", {
"runtime": "automatic"
}]]
}
if not, check the files that actually change when you add contact form. Mostly in config files like babel or webpack.
if using webpack and got a config like this in webpack.config.json
externals: {
'react': 'React'
},
remove it
If all else fails, remember react is not being bundled instead might be calling window.react so just add
import React from 'react';
import ReactDOM from 'react-dom';
window.React = React
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
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.