Code Coverage Part I

Use babel-plugin-istanbul to instrument code

Reference

babel-plugin-istanbul

Example by CRACO

React Code Coverage without ejecting from CRA

Steps

1.Get the front-end code repository

bash 复制代码
git clone git@github.com:EdmodoWorld/web-app.git
npm install

2.Setup local front-end environment

bash 复制代码
# 配置web-app/.env
PORT=3001
ENV=QA

REACT_APP_SKIP_ORACLE_TEST=0
SKIP_PREFLIGHT_CHECK=true
HTTPS=true

# 配置web-app/src/config/env.js
baseUrl                         : 'https://api.qa.mes1.edme.be',
clientId                        : <当前qa环境的clientId>,
bugsnagApiKey                   : '123456',

# 启动web-app正常,可访问https://localhost:3001
npm start

3.Install required plugin

bash 复制代码
npm i babel-plugin-istanbul @babel/preset-typescript @babel/preset-react babel-loader --save-dev

4.Config webpack field in file web-app/scripts/config-craco.js

bash 复制代码
// in getDevConfig function add below codes before <return webpackConfig> statement
// add istanbul to instrument code
        webpackConfig.module.rules.push({
          test: /\.(js|ts|tsx)$/,
          exclude: /node_modules/,
          use: {
            loader: "babel-loader",
            options: {
              presets: ["@babel/preset-typescript"],
              plugins: ["istanbul"]
            }
          }
        });

5.Add presets for babel config file web-app/babel.config.json

bash 复制代码
{
  "presets": ["@babel/preset-react"]
}

6.Start the web-app application

bash 复制代码
npm start

Troubleshoot

1.I can access web-app, but the window.coverage is not working in console, why the babel-plugin-istanbul is not working?

Solution: we should not use .babelrc file to add config because web-app is compiled by craco instead of babel, so we can just config in scripts/config-craco.js file

2.Failed to compile

Add @babel/preset-react (https://github.com/babel/babel/tree/main/packages/babel-preset-react)Connect your Github account to the 'presets' section of your Babel config to enable transformation.

Solution: add below content to the web-app/babel.config.json file

bash 复制代码
{
  "presets": ["@babel/preset-react"]
}
相关推荐
前端老宋Running8 小时前
“受控组件”的诅咒:为什么你需要 React Hook Form + Zod 来拯救你的键盘?
前端·javascript·react.js
风止何安啊8 小时前
拿捏 React 组件通讯:从父子到跨组件的「传功秘籍」
前端·react.js·面试
懒得不想起名字8 小时前
将flutter打成aar包嵌入到安卓
前端
Highcharts.js8 小时前
官方文档|Angular 框架集成 Highcharts Dashboards
前端·javascript·angular.js·highcharts·看板·使用文档·dashboards
韭菜炒大葱9 小时前
React 新手村通关指南:状态、组件与魔法 UI 🧙‍♂️
前端·javascript·react.js
天天扭码9 小时前
深入MCP本质——编写自定义MCP Server并通过Cursor调用
前端·mcp
1024肥宅10 小时前
JavaScript性能与优化:手写实现关键优化技术
前端·javascript·面试
一字白首10 小时前
Vue 项目实战,从注册登录到首页开发:接口封装 + 导航守卫 + 拦截器全流程
前端·javascript·vue.js
前端西瓜哥10 小时前
平面几何:如何绘制一个星形?
前端
天天扭码10 小时前
解放双手!使用Cursor+Figma MCP 高效还原响应式设计稿
前端·mcp