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"]
}
相关推荐
_安晓12 分钟前
Rust 中精确大小迭代器(ExactSizeIterator)的深度解析与实践
java·前端·python
烛阴13 分钟前
从create到yield:Lua协程完全上手指南
前端·lua
薛一半1 小时前
Vue3的Pinia详解
前端·javascript·vue.js
浅影歌年2 小时前
vue3模块中引用公共css变量文件
前端
盼哥PyAI实验室2 小时前
从搭建到打磨:我的纯前端个人博客开发复盘
前端·javascript
前端初见2 小时前
2025前端面试题大合集
前端
用户904706683573 小时前
vue3.5新特性——useTemplateRef
前端
嘉琪0013 小时前
vue3+ts面试题(一)JSX,SFC
前端·javascript·react.js
何贤3 小时前
🪐 行星科技概念官网!Hero Section 回归!(Three.js ✨)
前端·javascript·three.js
前端拿破轮3 小时前
ReactNative从入门到性能优化(一)
前端·react native·客户端