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"]
}
相关推荐
DoraBigHead3 小时前
🧭 React 理念:让时间屈服于 UI —— 从同步到可中断的演化之路
前端·javascript·面试
敢敢J的憨憨L4 小时前
GPTL(General Purpose Timing Library)使用教程
java·服务器·前端·c++·轻量级计时工具库
喝拿铁写前端4 小时前
Vue 组件通信的两种世界观:`.sync` 与普通 `props` 到底有什么不同?
前端·vue.js·前端框架
美酒没故事°4 小时前
npm源管理器:nrm
前端·npm·npm源
用户22152044278004 小时前
vue3组件间的通讯方式
前端·vue.js
三十_A4 小时前
【实录】使用 patch-package 修复第三方 npm 包中的 Bug
前端·npm·bug
下位子5 小时前
『AI 编程』用 Claude Code 从零到一开发全栈减脂追踪应用
前端·ai编程·claude
tyro曹仓舒5 小时前
Vue单文件组件到底需不需要写name
前端·vue.js
用户47949283569155 小时前
面试官:讲讲2FA 双因素认证原理
前端·后端·安全