I am trying to integrate jest for a react SPA.
React app is create using
npx create-react-app my-app
I am trying to integrate Jest into it. "jest" and "babel-jest" dependencies are default integrated inside package.json.
It is using version 23.* and I am not able to update it.
I am getting error while running a simple test. It calls for css file which is not resolved.
I tried,
1)
"moduleNameMapper": {
"\\.(css)$": "<rootDir>/node_modules/jest-css-modules"
}
2)
"moduleNameMapper": {
"\\.(css)$": "<rootDir>/src/__mocks__/styleMock"
}
3)
"moduleNameMapper": {
"\\.(css)$": "<rootDir>/src/__mocks__/styleMock.js"
}
4)
"moduleNameMapper": {
"\\.(css)$":"identity-obj-proxy"
}
I run using "npm test" command.
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject"
}
I also tried adding below,
"transform": { ".*": "<rootDir>/node_modules/babel-jest" }
and,
"moduleFileExtensions": [
"js",
"jsx",
"json",
"node",
"scss",
"ts",
"tsx"
]
but nothing works.
1 | import React, { Component } from "react";
> 2 | import "./login.css";
| ^
3 | import Image from "react-bootstrap/Image";
4 |
5 | import default_picture from "./../assets/default_picture.jpg";
at Resolver.resolveModule (node_modules/jest-resolve/build/index.js:221:17)
at Object.<anonymous> (src/components/AppLogin.jsx:2:1)
Related
I have React project created without cra. I need to add code coverage for cypress e2e tests.
In app created with cra I do the following instructions for add code coverage. And add this line of code in package.json
"start": "react-scripts -r #cypress/instrument-cra start",
This work's well with cra.
But in app without cra I can't add react-scripts or #cypress/instrument-cra for get code coverage information.
How to realize this?
My current configuration ->
babel.config.json
{
"presets": [
"#babel/preset-env",
[
"#babel/preset-react",
{
"runtime": "automatic"
}
],
"#babel/preset-typescript"
],
"plugins": [
"istanbul",
"transform-class-properties",
[
"#babel/plugin-transform-runtime",
{
"useESModules": true,
"regenerator": false
}
]
],
"env": {
"development": {
"plugins": ["istanbul", "transform-class-properties"]
},
"test": {
"presets": [
["#babel/preset-env", {
"targets": "current node"
}]
]
}
}
}
e2e.ts
// Import commands.js using ES2015 syntax:
import "#cypress/code-coverage/support";
import './commands'
// Alternatively you can use CommonJS syntax:
// require('./commands')
Cypress.on('uncaught:exception', () => {
/**
* Returning false here prevents Cypress from
* failing the test when one of requests fails
*/
return false
});
package.json
"scripts": {
"start": "webpack-cli serve --port 9007 --env currentEnv=local",
"build": "webpack --mode production",
"serve": "serve dist -p xxxx",
"clean": "rm -rf dist",
"test": "cross-env BABEL_ENV=test jest",
"cy:open": "cypress open",
"cy:run": "cypress run",
"pretest:e2e:run": "npm run build",
"test:e2e:run": "start-server-and-test start http://localhost:9000 cy:run",
"test:e2e:dev": "start-server-and-test start http://localhost:9000 cy:open",
"watch-tests": "cross-env BABEL_ENV=test jest --watch",
"check:coverage": "nyc report --reporter=text-summary --check-coverage",
"prepare": "husky install"
},
// ...
"nyc": {
"all": true,
"excludeAfterRemap": true,
"check-coverage": true,
"extension": [
".tsx"
],
"include": [
"src/views/**/*.tsx"
]
}
cypress.config.ts
export default defineConfig({
e2e: {
setupNodeEvents(on, config) {
// implement node event listeners here,
require("#cypress/code-coverage/task")(on, config);
// include any other plugin code...
// It's IMPORTANT to return the config object
// with any changed environment variables
return config;
},
video: false,
baseUrl: "http://localhost:3000/",
},
});
Currently, in browser after each test does finished I get the following error
Could not find any coverage information in your application by looking at the window coverage object. Did you forget to instrument your application? See code-coverage#instrument-your-application [#cypress/code-coverage]
In my React app I want to use import assertion:
import data from "./json/clients-m.json" assert { type: "json" }
However, I get the following error:
ERROR in ./src/Clients.js
Module build failed (from ./node_modules/babel-loader/lib/index.js):
SyntaxError: E:\src\Clients.js: Support for the experimental syntax 'importAssertions' isn't currently enabled.
Add #babel/plugin-syntax-import-assertions (https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-import-assertions) to the 'plugins' section of your Babel config to enable parsing.
Line 1:41: Parsing error: This experimental syntax requires enabling the parser plugin: "importAssertions". (1:41)
I have installed this plugin:
npm install #babel/plugin-syntax-import-assertions --save-dev
Then I created .babelrc.json:
{
"plugins": [
"#babel/plugin-syntax-import-assertions"
]
}
And also added this plugin into package.json:
{
"name": "clients-frontend",
"version": "0.1.0",
"private": true,
"babel": {
"plugins": [
"#babel/plugin-syntax-import-assertions"
]
},
"dependencies": {
"#testing-library/jest-dom": "^5.16.4",
"#testing-library/react": "^13.1.1",
"#testing-library/user-event": "^13.5.0",
"bootstrap": "^5.1.3",
"react": "^18.1.0",
"react-dom": "^18.1.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"devDependencies": {
"#babel/plugin-syntax-import-assertions": "^7.16.7"
}
}
However, I keep getting this error. 😐
react-scripts doesn't load babel configuration by default. Install the following packages
npm i -D customize-cra react-app-rewired
These packages let you customize react-scripts's default configuration for babel so you can use additional plugins
Now, change the scripts in your package.json
"scripts": {
- "start": "react-scripts start",
+ "start": "react-app-rewired start",
- "build": "react-scripts build",
+ "build": "react-app-rewired build",
- "test": "react-scripts test",
+ "test": "react-app-rewired test"
}
Create a file config-overrides.js at the root of your app with the following content
/* config-overrides.js */
/* eslint-disable react-hooks/rules-of-hooks */
const { useBabelRc, override } = require('customize-cra');
module.exports = override(useBabelRc());
Now, create .babelrc at the root of your package
{
"plugins": [
"#babel/plugin-syntax-import-assertions"
]
}
Now, your babel configuration will be loaded correctly. There's another library craco that lets you customize the react-scripts configuration
Try installing the babel-eslint package as well. And, in your .eslintrc.json file add:
{
"parserOptions": {
"babelOptions": {
"parserOpts": {
"plugins": ["importAssertions"]
}
}
}
}
npm install #babel/plugin-syntax-import-assertions --save-dev
babel.config.cjs
module.exports = function (api) {
api.cache(true);
let presets = [];
let plugins = [];
switch (process.env['NODE_ENV']) {
case 'test':
presets = [
[
'#babel/preset-env',
{
targets: {
node: 'current',
},
},
],
];
plugins = [
'babel-plugin-transform-import-meta',
'#babel/plugin-proposal-export-default-from',
'#babel/plugin-syntax-import-assertions'
];
break;
default:
presets = [
[
'#babel/preset-env',
{
modules: false, //Setting this to false will preserve ES services
targets: {
node: 'current',
},
},
],
];
plugins = ['#babel/plugin-syntax-import-assertions'];
break;
}
return {
presets,
plugins,
};
};
If you (like me) use an ejected react-script app, maybe you need to set your configuration in webpack.config.js in the application-scope babel-loader:
// Process application JS with Babel.
// The preset includes JSX, Flow, TypeScript, and some ESnext features.
{
test: /\.(js|mjs|jsx|ts|tsx)$/,
include: paths.appSrc,
loader: require.resolve('babel-loader'),
options: {
customize: require.resolve('babel-preset-react-app/webpack-overrides',),
presets: [/* ... */],
plugins: [ // ADD THIS 👇
require.resolve('#babel/plugin-syntax-import-assertions'),
[require.resolve('babel-plugin-direct-import'), {
modules: [
require.resolve('#mui/material'),
require.resolve('#mui/icons-material'),
require.resolve('#mui/lab'),
require.resolve('#mui/base'),
require.resolve('#mui/system'),
],
}],
isEnvDevelopment && shouldUseReactRefresh && require.resolve('react-refresh/babel'),
].filter(Boolean),
// ...
},
},
But NOT here:
// Process any JS outside of the app with Babel.
// Unlike the application JS, we only compile the standard ES features.
{
test: /\.(js|mjs)$/,
exclude: /#babel(?:\/|\\{1,2})runtime/,
// ...
In my react project I wanna use sweetalert library like that import Swal from "sweetalert2/src/sweetalert2"; instead of using like that import Swal from "sweetalert2"
That's why instead of changing it everywhere, i wanted to manage it from webpack. So I wrote alias for it
resolve: {
alias: {
'sweetalert': path.resolve(__dirname,'./node_modules/sweetalert2/src/sweetalert2.js'),
},
},
And tried to import the library, but it seems doesn't work. Maybe my webpack.config.js file doesn't work.
import Swal from "sweetalert";
I also tried like that;
'sweetalert': 'sweetalert2/src/sweetalert2.js',
I am using
react 17.0.2
webpack 5.65.0
And the scripts file in package.json
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"analyze": "cross-env REACT_APP_INTERACTIVE_ANALYZE=1 npm run build",
"eject": "react-scripts eject",
"lint": "eslint src",
"lint:fix": "npm run lint -- --fix",
"format": "prettier --write \"src/**/*.{js,css,scss,html}\"",
"rtl": "webpack"
},
Note: I named it 'sweetalert' for testing.
I created a simple project to study monorepo. The example consists of three React applications, where one consists of a lib of components with the Storybook and the other two will import the components of this package.
However I am not able to import a component from another package.
When I import a common function, no error occurs.
Github repository
Error message
../components/src/button/Button.js
SyntaxError: /home/thiago/Documentos/Dev/projects/learn-monorepo/packages/components/src/button/Button.js: Support for the experimental syntax 'jsx' isn't currently enabled (7:5):
5 | function Button({label, ...rest}) {
6 | return (
> 7 | <div>
| ^
8 | <button {...rest}>
9 | {label}
10 | </button>
Add #babel/preset-react (https://git.io/JfeDR) to the 'presets' section of your Babel config to enable transformation.
If you want to leave it as-is, add #babel/plugin-syntax-jsx (https://git.io/vb4yA) to the 'plugins' section to enable parsing.
Button component
function Button({label, ...rest}) {
return (
<div>
<button {...rest}>
{label}
</button>
</div>
);
}
export { Button };
App.js
import React from 'react';
import { Button } from '#project/components';
function App() {
return (
<div>
<h1>Hello World - App 01</h1>
<Button label="Button"/>
</div>
);
}
export default App;
Package.json
{
"name": "project",
"version": "1.0.0",
"main": "build/index.js",
"author": "thiago <thenrique2012#gmail.com>",
"license": "MIT",
"private": true,
"workspaces": {
"packages": ["packages/*"]
},
"babel": {
"presets": [
"#babel/preset-react"
],
"plugins": [
"#babel/plugin-syntax-jsx"
]
},
"scripts": {
"bootstrap": "lerna bootstrap",
"start:app-01": "lerna run --scope #project/app-01 start",
"start:app-02": "lerna run --scope #project/app-02 start",
"start:storybook": "lerna run --scope #project/components storybook",
"start:web": "yarn start:app-01 & yarn start:app-02 & yarn start:storybook"
},
"devDependencies": {
"#babel/plugin-syntax-jsx": "^7.12.1",
"#babel/preset-react": "^7.12.10",
"babel-loader": "8.1.0",
"lerna": "^3.22.1"
}
}
You get error because you have not transpiled your shared react components. There are some (not official) solutions for this with create-react-app. One of them is to use react-app-rewired and customize-cra. Instal lthem as dev-dependency and add a config-overrides.js file to the root of your create-react-app:
var path = require('path')
const { override, babelInclude } = require('customize-cra')
module.exports = function (config, env) {
return Object.assign(
config,
override(
babelInclude([
/* transpile (converting to es5) code in src/ and shared component library */
path.resolve('src'),
path.resolve('../components'),
])
)(config, env)
)
}
Then use react-app-rewired instead of react-scripts in your scripts for start and build of the project:
"scripts": {
"start": "react-app-rewired start",
"build-prod": "react-app-rewired build",
"build": "react-app-rewired build",
"test": "react-app-rewired test",
"eject": "react-scripts eject"
},
I am try create app with react-tool-box. Also I try use Jest for testing,
but get this test fails. It look like es6 configuration problem for Jest.
● Test suite failed to run
/home/user/project/react-tool-box/react-toolbox-example/src/frontend/components/PurpleAppBar.js: Unexpected token (5:34)
3 | import theme from './PurpleAppBar.css';
4 |
> 5 | const PurpleAppBar = ({ children, ...other }) => (
| ^
6 | <AppBar {...other} theme={theme}>
7 | Hello developer!
8 | {children}
my jest.config.js:
{
"moduleFileExtensions": [
"js",
"jsx"
],
"scriptPreprocessor": "<rootDir>/node_modules/babel-jest",
"moduleNameMapper": {
"App": "<rootDir>/src/frontend/components/App.js"
}
}
my .bablerc:
{
"presets": [
"react",
"es2015"
]
}
and package.json scripts:
...
"scripts": {
"start": "node_modules/.bin/cross-env NODE_ENV=development node_modules/.bin/webpack-dev-server --colors --config webpack.config.js",
"build": "node_modules/.bin/cross-env NODE_ENV=production UV_THREADPOOL_SIZE=100 webpack --config webpack.config.js",
"deploy": "gh-pages -d build",
"test": "jest --config jest.config.js"
},
...
I found answer here.
add "stage-3" to .babelrc:
{
"presets": ["es2015", "stage-3", "react"]
}