create-react-app & jest — SyntaxError: Unexpected token import - reactjs

NOTE: I fixed this by moving all of the code inside my src/nod_modules folder into the src folder directly and deleting src/node_modules as per this short thread: https://github.com/facebook/create-react-app/issues/4241
I am using create-react-app and having trouble running Jest.
When I attempt to import any one of my React components into my test file, I get an error when I yarn test:
Test suite failed to run
.../src/node_modules/common/ErrorMessage.js:1
({"Object.<anonymous>":function(
module,exports,require,__dirname,__filename,global,jest)
{import React from 'react'
^^^^^^
SyntaxError: Unexpected token import
This is what my test file looks like:
// test.test.js
// attempting to import
import ErrorMessage from '../node_modules/common/ErrorMessage.js'
// dummy test
test('adds 1 + 2 to equal 3', () => {
expect(1 + 2).toBe(3)
})
However, the error does not get thrown if I'm at the root of the src file, importing my index.js. At that point, the error gets thrown in the first file that index.js imports. For example:
test.test.js
import index from './index'
index.js
import React from 'react'
import { render } from 'react-dom'
import './style/index.css'
import LoginContainer from './node_modules/user/LoginContainer'
import NewUser from './node_modules/user/NewUser'
// etc.
terminal output
FAIL src/test.test.js
● Test suite failed to run
/Users/hannahmccain/Desktop/DEV/expense-report/fullstack-expense-report/client/src/node_modules/user/LoginContainer.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import React, { Component } from 'react'
^^^^^^
SyntaxError: Unexpected token import
at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/ScriptTransformer.js:289:17)
at Object.<anonymous> (src/index.js:11:164)
at Object.<anonymous> (src/test.test.js:3:14)
It seems like, in the context of Jest, Babel isn't able to compile the files in src/node_modules properly. I'm just at a loss as to how to correct that! Any insights would be appreciated.
FYI, Jest is supposed to work out-of-the-box with create-react-app, and I don't want to eject. Without ejecting, I'm unable to make certain changes I've seen recommended elsewhere, such as updating the Jest settings in my package.json.

To follow up with #Himanshu Singh answer, by adding this in my package.json helped me resolved this error.
{
test: react-scripts test --transformIgnorePatterns \"node_modules/(?!ui-core)/\" --env=jsdom
}

The code inside node_modules/user/LoginContainer.js is not a production release (babelified version) as it still has those import statement.
Jest that comes pre-configured with create-react-app, excludes everything inside node_modules from babel-transformation before running tests assuming that the code inside node_modules would be pre-babelified.
And since your module inside node_modules isn't babelified, jest throws error as soon as it encounters import statement.
Solution
1. You must be having a build script for your node_module in use. Try placing the production release of your module inside node_modules.This will do the trick but will also create further issues (as per my experience).
2. Start configuring jest and its dependencies explicitly without ejecting. Essentially by changing your test script to jest --env=jsdom. You will need to install jest, react-dom, babel-transforms-* explicitly and then configure using jest configuration inside package.json.
Here you need to focus on two major configuration option - transformIgnorePatterns and transform.
In short, transform everything and ingnore everything that is already transformed.
Take a look at Jest configuration section for more details.

Related

create react app tests not running without any changes to the code

I ran create-react-app.
Made no changes and ran the tests.
The tests failed straight away.
Error: Failed to initialize watch plugin "node_modules/jest-watch-typeahead/filename.js":
● Test suite failed to run
file:///C:/_Projects/my-app/node_modules/jest-watch-typeahead/build/file_name_plugin/prompt.js:4
import { PatternPrompt, printPatternCaret, printRestoredPatternCaret } from 'jest-watcher';
^^^^^^^^^^^^^
SyntaxError: The requested module 'jest-watcher' is expected to be of type CommonJS, which does not support named exports. CommonJS modules can be imported by importing the default export.
For example:
import pkg from 'jest-watcher';
const { PatternPrompt, printPatternCaret, printRestoredPatternCaret } = pkg;
at async requireOrImportModule (node_modules/jest-util/build/requireOrImportModule.js:65:32)
at async watch (node_modules/#jest/core/build/watch.js:337:34)
at async _run10000 (node_modules/#jest/core/build/cli/index.js:311:7)
What the deuce?
Can anyone please help?
This is a known issue and is related to the version of node you are using. Check out https://github.com/facebook/create-react-app/issues/11792.
Resolve it by upgrading to the latest node version >16. This worked for me. https://nodejs.org/en/download/

Storybook Can't Import Swiper Module

I am trying to import Swiper for react in to my application and use it in Storybook.
I have the following import:
import { Swiper, SwiperSlide } from 'swiper/react';
This works in the React app but not in Storybook, I get the following error:
ModuleNotFoundError: Module not found: Error: Can't resolve 'swiper/react'
Other React modules have import without a problem. Do I need to change some configuration in Storybook?
Swiper v7+ uses ESM module. To make it work with storybook, you have to update storybook to use webpack5 instead of the default webpack4. Also ensure that your current node version must be equal or higher than 12.20, 14.13 or 16. These are versions that support ESM module.
In my case, I also delete addons #storybook/react line in .storybook/main.js as it still uses webpack4 and raises configuration Validation Error. After that it runs fine.
Full instruction
https://gist.github.com/shilman/8856ea1786dcd247139b47b270912324#upgrade
https://storybook.js.org/blog/storybook-for-webpack-5/

Trouble-shooting "Cannot use import statement outside a module"

I am trying to use puppeteer for e2e testing on a react app. I'd prefer to use TypeScript, so I've tried to start with a file that begins with:
import puppeteer, { Browser, Page } from "puppeteer";
I can't seem to resolve this error, though:
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import puppeteer from "puppeteer";
^^^^^^
SyntaxError: Cannot use import statement outside a module
at Runtime.createScriptFromCode (../node_modules/jest-runtime/build/index.js:1350:14)
I'm eager to learn, but not sure how to trouble-shoot this.
I don't think Jest supports ES6.
Have you checked Jest docs for support -> https://jestjs.io/docs/ecmascript-modules

Trying to integrate jest and react with amchart but getting an error . What could be the issue?

Following is the error that I am getting while I run npm test:
export { System, system } from "./.internal/core/System";
^^^^^^
SyntaxError: Unexpected token export
1 | import React from 'react';
> 2 | import * as am4core from "#amcharts/amcharts4/core";
3 | import * as am4charts from "#amcharts/amcharts4/charts";
at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/node_modules/#jest/transform/build/ScriptTransformer.js:537:17)
AmCharts supply their package in ES2015 standart, so it doesnt support IE9 or any old browser.
React default scripts enforces that all used libraries come compiled compatible with CommonJS.
By default Jest doesnt compile any of node_modules and attempts to run amCharts code as is and fails.
If you are ejected from react-scripts then you can update jest config:
"jest": {
"transformIgnorePatterns": [
"[/\\\\]node_modules[/\\\\](?!(#amcharts)\\/).+\\.(js|jsx|ts|tsx)$"
],
...
}
If you dont want to eject you will need to use transformIgnorePatterns as cli option:
react-scripts test --transformIgnorePatterns '[/\\\\]node_modules[/\\\\](?!(#amcharts)\\/).+\\.(js|jsx|ts|tsx)$'"
Note: One of the reasons why react team is agianst using this option is that, you code under test will be different from one in production (compiled vs not compiled), but as far as you dont test charts and just mock them as dependancy this should be fine.

Using own React npm component - appropriate loader issues

I have made a component in my React app that I would like to publish to NPM. It's consists of just one file index.js
import React from 'react'
import PropTypes from 'prop-types';
export default class Test extends React.Component {
//I seem to be getting a specific issue with the lines below
//Do I need a special loader for these?
static displayName = 'Test'
static defaultProps = {
live: true,
}
}
Originally the component was in a components directory of my main app and I include it using:
import Test from './components/Test'
Since then I have created a new folder (not part of my main app) and added a package.json file and the index.js file. I have also published it to NPM which worked fine but when I try to use it after installing...
npm i -S package-name
import Test from 'package-name'
I get an error: You may need an appropriate loader to handle this file type...
My package.json file doesn't have any dependencies or devDependencies at the moment. Do I need to do something with Webpack and Babel?
Do I need to do something with Webpack and Babel?
Most likely. If you are using ES6 syntax in package-name then babel needs to transcode that library as well. When I have encountered that error this has always been the case. I suggest updating your Webpack / Babel configuration to include that library.

Resources