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"]
}
相关推荐
breeze jiang13 分钟前
React Todos 前端独立开发全解:用 vite-plugin-mock + axios 封装,再也不等后端接口
前端·react.js·状态模式
cyadyx20 分钟前
【vue】Pinia相对Vuex
前端·javascript·vue.js
码上成长30 分钟前
小程序请求层怎么封装?
前端·小程序
IT_陈寒1 小时前
Redis的KEYS命令差点把我的生产环境拖垮,改用SCAN吧
前端·人工智能·后端
deli0070071 小时前
打飞碟射击场:霓虹星空下飞碟满天飞,鼠标点射一枪一个
前端·ai编程
zoe驿鹿1 小时前
【CI/CD】前端工程化与自动化:从“手工作坊”到“现代化工厂”的演进之路
前端·ci/cd·自动化
lupai1 小时前
增值税发票 OCR 识别 API 新手接入指南
java·前端·ocr
IMPYLH1 小时前
HTML 的 <figure> 元素
前端·javascript·html
reasonsummer1 小时前
【办公类-120-01】20260812闵行区幼儿园概况表的数据统计(户籍、五类性质、优抚子女)
前端·python
宿6741 小时前
vue3-指令和事件处理
开发语言·前端·javascript