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]
Related
I'm working on a React typescript project and I want to generate a results of the tests and coverage as an xml file in project root. I have installed jest-junit and jest-junit-reporter. But unfortunately, I'm unable to generate a coverage report.
Here you can fing my package.json file
{
"name": "#",
"version": "0.0.0",
"license": "MIT",
"scripts": {
"start": "nx serve",
"build": "nx build",
"test": "jest --coverage --jest-junit.xml",
"devstart": "nx serve shell --open --devRemotes=dashboard"
},
....
"jest": {
"testResultsProcessor": "./node_modules/jest-junit-reporter",
"coverageReporters": [
"text"
],
"reporters": [
"default",
"jest-junit"
]
},
"jest-junit" :{ "outputDirectory": "test_results", "outputName": "jest-junit.xml"}
}
Can someone assist me in this issue? What's the error I have done in here?
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/,
// ...
Previously, i deployed my project on compute engine where there was no any issue on page loading. The page used to load very fast. However, when i move to serverless, the page is loading very very slow and also sometime i get 'Error: could not handle the request'. I am not confident enough on serverless deployment.
Here is how I am deploying
structure
.firebase
.next
public
src
components
pages
utils
next.config.js
server.js
.firebaserc
firebase.json
package.json
configuration part
.firebaserc
{
"projects": {
"default": "project-test"
}
}
firebase.json
{
"hosting": {
"public": "public",
"ignore": ["firebase.json", "**/.*", "**/node_modules/**"],
"rewrites": [
{
"source": "**",
"function": "next"
}
]
},
"functions": {
"source": ".",
"ignore": [
".firebase/**",
".firebaserc",
"firebase.json",
"**/node_modules/**",
"**/.vscode/**",
"**/.hooks/**",
"**/public/**"
]
}
}
next.config.js
const withPlugins = require("next-compose-plugins");
const optimizedImages = require("next-optimized-images");
const withPWA = require("next-pwa");
module.exports = withPlugins(
[optimizedImages],
[
withPWA({
pwa: {
dest: "public",
},
}),
]
);
server.js (i dont know where this is being used)
const functions = require('firebase-functions');
const next = require('next');
var dev = false;
console.log('dev', process.env.NODE_ENV);
var app = next({ dev, conf: { distDir: '.next' } });
var handle = app.getRequestHandler();
exports.next = functions.https.onRequest((req, res) => {
console.log('File: ' + req.originalUrl); // log the page.js file that is being requested
return app.prepare().then(() => handle(req, res));
});
scripts
"scripts": {
"dev:client": "next",
"local": "dotenv -e .env.local next",
"dev:server": "node src/server --source-maps --watch",
"dev": "dotenv -e .env.development yarn dev:client & yarn dev:server",
"build": "dotenv -e .env.production next build",
"build:dev": "dotenv -e .env.development next build",
"build:staging": "dotenv -e .env.staging next build",
"build:production": "NODE_ENV=production dotenv -e .env.production next build",
"deploy:dev": "dotenv -e .env.development firebase deploy --only functions,hosting",
"deploy:staging": "dotenv -e .env.staging firebase deploy -P staging --only functions,hosting",
"start": "next start",
},
the way I am deploying is
first i build the project using following command
yarn build:dev
then deploy using yarn deploy:dev
here is the build file
Did i miss any important thing while deploying?
Note: I am using nextjs 9.4
After compiling SPA (React) to production with NODE_ENV=production there is error:
n.e(...).then(...).config is not a function
n - Promise in UglifyJS
This is package.json
"scripts": {
"dev": "webpack-dev-server --mode development --colors",
"start": "cross-env NODE_ENV=production webpack-dev-server --mode production --env.NODE_ENV=production --colors",
"build": "cross-env NODE_ENV=production webpack --mode production --env.NODE_ENV=production --colors --optimize-minimize",
"test": "test",
"analyze:build": "cross-env ANALYZE=true npm run build",
"analyze:start": "cross-env ANALYZE=true npm run start",
"analyze:dev": "cross-env ANALYZE=true npm run dev"
},
.babelrc
{
"presets": [
["#babel/preset-env", {
"targets": {
"browsers": "last 2 versions"
}
}],
"#babel/preset-react"
],
"plugins": [
"#babel/plugin-transform-runtime",
"#babel/plugin-syntax-dynamic-import",
"#babel/plugin-proposal-class-properties",
"react-hot-loader/babel"
]
}
webapack.config.js
entry: {
app: [
'./index.js'
],
core: [
'react',
'react-dom',
'core-js',
'react-router',
'redux',
'react-redux'
]
},
optimization: {
splitChunks: {
cacheGroups: {
commons: {
test: 'core',
name: 'core',
chunks: 'initial'
},
async: {
test: /[\\/]node_modules[\\/]/,
chunks: 'async',
priority: -10
},
vendors: {
test: /[\\/]node_modules[\\/]/,
name: "vendors",
chunks: 'initial',
priority: -20
}
}
}
},
dont know what im doing wrong =(
i was trying and with #babel/polyfill - same
screenshot of error
Some libraries are not supported latest webpack.
Problem with with support .mjs files. So when you downgrade to version 3.x problem should be solved
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"]
}