Jest testing throws error because of gatsby webpack configuration - reactjs

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;

Related

Rainbow Kit. React app failures jest test with rainbow-kit component

A react app (built with create-react-app ts) fails jest test after a rainbow kit component was added.
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){import {
^^^^^^
SyntaxError: Cannot use import statement outside a module
1 | import { useState } from 'react';
2 | import cn from 'classnames';
> 3 | import { ConnectButton } from '#rainbow-me/rainbowkit';
| ^
4 |
5 | import { UrlForm } from 'components';
6 | import classes from 'App.module.scss';
What could be going wrong with it?
Tests run and pass successfully after ConnectButton removed.

Jest - Cannot use import statement outside a module - using Rescript

I am trying to run unit tests in a React project generated using react-scripts, in which I added ReScript support.
When I run the tests, however, I encountered an error in the transpiled javascript code.
Details of the error:
/Users/massimilianodacunzo/Projects/Elixir/test-project/apps/phoenix_react_web/assets/node_modules/bs-platform/lib/es6/array.js:3
import * as Curry from "./curry.js";
^^^^^^
SyntaxError: Cannot use import statement outside a module
1 |
2 |
> 3 | import * as $$Array from "../../../node_modules/bs-platform/lib/es6/array.js";
| ^
4 | import * as React from "react";
5 |
6 | function TestComponent(Props) {
at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1350:14)
at Object.<anonymous> (src/components/users/TestComponent.bs.js:3:1)
The components I am trying to test:
App.res
%%raw(`
import logo from './logo.svg';
import './App.css';
`)
#react.component
let make = () => {
<div className="App">
<TestComponent elements={["1", "2", "3"]} />
</div>
}
TempComponent.res
#react.component
let make = (
~elements: array<string>
) => {
<ul>
{
React.array(
elements
|> Array.map(e =>
<li key={e}>{React.string(e)}</li>)
)
}
</ul>
}
The generated TestComponent.bs.js
import * as $$Array from "../../../node_modules/bs-platform/lib/es6/array.js";
import * as React from "react";
function TestComponent(Props) {
var elements = Props.elements;
return React.createElement("ul", undefined, $$Array.map((function (e) {
return React.createElement("li", {
key: e
}, e);
}), elements));
}
var make = TestComponent;
export {
make ,
}
/* react Not a pure module */
Is there any additional configuration I can add to the react-scripts test script?
Following the comment of glennsl, I followed the git issue, discovering that the configuration in my bsconfig.json file specified the package-specs module as es6. The test error didn't appear if I change the configuration to commonjs.
{
...
"package-specs": {
"module": "commonjs",
"in-source": true
}
...
}
Again, thanks to glennsl for pointing me in the right direction.

React Jest test didn't recognize import Alias

I'm executing a basic React Jest test in a Button component and the test don't recognize an import.
Does anyone have any idea why the test fail in this import ?
Component:
import ...
import ... from 'styled-components';
import ... from 'styled-tools';
import {Icon} from 'xpto';
import {Default as theme} from 'Themes';
import * as mixins from '../../../config/styles/mixins';
...
&:hover{
background-color: #000;
border: 1px solid ${theme.colors.primary};
color: ${theme.colors.primary};
& svg:not([fill="none"]):not([fill="#000"]) {
fill: ${theme.colors.primary};
}
& .nohover svg {
fill: ${({color}) => color};
}
...
Error:
FAIL .../Button/index.test.js
● Test suite failed to run
Cannot find module 'Themes' from 'index.js'
5 |
6 | import {Icon} from 'xpto';
> 7 | import {Default as theme} from 'Themes';
| ^
8 |
9 | import * as mixins from '../../../config/styles/mixins';
10 |
at Resolver.resolveModule (node_modules/jest-resolve/build/index.js:221:17)
at Object.<anonymous> (.../Button/index.js:7:1)
Jest test file:
import React from 'react';
import { mount } from 'enzyme';
import Button from './index';
describe('Button', () => {
it('should render correctly with no props', () => {
const component = mount(<Button/>);
expect(component).toMatchSnapshot();
});
});
Jest couldn't resolve your index.js in Themes folder. You can fix it by using one of two ways below:
Tell Jest how to resolve your file:
setting in package.json
"jest": {
"modulePaths": ["path to src folder which contains Themes folder"],
...
}
Check out this tutorial
Set NODE_PATH in .env file
NODE_PATH=src/ # src folder contains Themes folder

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

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

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