npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

yd-coverage-reporter

v0.0.8

Published

前端代码覆盖率上报 SDK

Readme

Coverage Reporter SDK

前端代码覆盖率上报 SDK,用于在测试环境中自动收集和上报代码覆盖率数据。

功能特性

  • ✅ 自动收集 window.__coverage__ 覆盖率数据
  • 只收集语句覆盖率(移除函数和分支覆盖率,减少数据量)
  • ✅ 定时上报(默认 30 秒,可配置)
  • ✅ 页面关闭/隐藏时自动上报(使用 fetch keepalive)
  • ✅ 数据变化检测(只上报有变化的数据)
  • 智能过滤:只上报有执行记录的文件
  • 增量上报:只发送变化的文件
  • 分批上报:大数据自动分批,防止超时
  • ✅ TypeScript 支持
  • ✅ 调试模式

安装

npm install yd-coverage-reporter --save-dev
# or
yarn add yd-coverage-reporter -D

使用步骤

1. 配置 babel-plugin-istanbul

首先需要在项目中配置 babel-plugin-istanbul 来对代码进行插桩。

安装依赖

npm install babel-plugin-istanbul --save-dev

Create React App 项目配置

对于 CRA 项目,需要使用 customize-cra 或 eject 后修改配置:

方式一:使用 customize-cra(推荐)

npm install customize-cra react-app-rewired --save-dev

创建 config-overrides.js

const { override, addBabelPlugin } = require("customize-cra");

module.exports = override(
  // 只在测试环境启用覆盖率插桩
  process.env.REACT_APP_COVERAGE === "true" &&
    addBabelPlugin([
      "babel-plugin-istanbul",
      {
        exclude: ["**/*.spec.js", "**/*.test.js", "node_modules/**"],
      },
    ]),
);

修改 package.json 的 scripts:

{
  "scripts": {
    "start": "react-app-rewired start",
    "build": "react-app-rewired build",
    "start:coverage": "REACT_APP_COVERAGE=true react-app-rewired start",
    "build:coverage": "REACT_APP_COVERAGE=true react-app-rewired build"
  }
}

方式二:直接修改 Webpack 配置

如果你已经 eject 或使用自定义 Webpack 配置,在 babel-loader 配置中添加:

{
  test: /\.(js|jsx|ts|tsx)$/,
  use: {
    loader: 'babel-loader',
    options: {
      plugins: [
        process.env.REACT_APP_COVERAGE === 'true' && [
          'babel-plugin-istanbul',
          {
            exclude: ['**/*.spec.js', '**/*.test.js', 'node_modules/**'],
          },
        ],
      ].filter(Boolean),
    },
  },
}

2. 在项目入口初始化 SDK

在你的项目入口文件(通常是 src/index.jssrc/App.js)中初始化:

import React from "react";
import ReactDOM from "react-dom";
import { init } from "yd-coverage-reporter";
import App from "./App";

// 只在测试环境启用覆盖率上报
if (process.env.REACT_APP_COVERAGE === "true") {
  init({
    serverUrl: "http://your-backend.com/api/coverage/report",
    gitProjectId: "my-project",
    baseBranch: "main", // 需要对比的基础分支名称,后台用于计算 diff
    featureBranch: "feature-login",
    environment: "test",
    reportInterval: 30000, // 30秒上报一次
    debug: true, // 开启调试日志
  })
    .then(() => {
      console.log("覆盖率采集已启动");
    })
    .catch((err) => {
      console.error("覆盖率采集启动失败:", err);
    });
}

ReactDOM.render(<App />, document.getElementById("root"));

3. 启动项目

npm run start:coverage

现在你可以在测试环境中操作页面,SDK 会自动收集和上报覆盖率数据!

API

init(config: CoverageConfig): Promise<void>

初始化 SDK。

配置选项

interface CoverageConfig {
  /** 上报服务器地址(必填) */
  serverUrl: string;

  /** 项目唯一标识(必填) */
  gitProjectId: string;

  /** 需要对比的基础分支名称(必填),用于后台计算 diff */
  baseBranch: string;

  /** 当前特性分支名称(必填) */
  featureBranch: string;

  /** 环境标识(可选,默认:'test') */
  environment?: string;

  /** 定时上报间隔,单位毫秒(可选,默认:30000ms) */
  reportInterval?: number;

  /** 是否启用调试模式(可选,默认:false) */
  debug?: boolean;

  /** 自定义请求头(可选) */
  headers?: Record<string, string>;
}

示例

await init({
  serverUrl: "http://localhost:8617/api/coverage/report",
  gitProjectId: "my-project",
  baseBranch: "main", // 需要对比的基础分支名称,后台用于计算 diff
  featureBranch: "feature-login",
  environment: "test",
  debug: true,
  reportInterval: 10000, // 10秒上报一次(仅用于测试)

  // 🚀 性能优化配置(可选)
  onlyActiveFiles: true, // 只上报有执行记录的文件(默认 true)
  enableDeltaReporting: true, // 启用增量上报,只发送变化的文件(默认 true)
  maxReportSize: 1024 * 1024, // 单次上报最大数据大小 1MB,超过则分批(默认 1MB)
  batchSize: 20, // 分批上报时每批的文件数量(默认 20)
});

report(): Promise<void>

手动触发一次上报。

import { report } from "yd-coverage-reporter";

// 在某个操作完成后手动上报
await report();

getCoverage(): any

获取当前的覆盖率数据。

import { getCoverage } from "yd-coverage-reporter";

const coverage = getCoverage();
console.log(coverage);

destroy(): void

销毁 SDK 实例,停止定时上报。

import { destroy } from "yd-coverage-reporter";

destroy();

上报数据格式

SDK 会将覆盖率数据按以下格式上报到服务器:

interface CoverageReport {
  /** 项目ID */
  gitProjectId: string;

  /** 环境 */
  environment: string;

  /** 上报时间戳 */
  timestamp: number;

  /** 会话ID(用于区分不同的测试会话) */
  sessionId: string;

  /** 覆盖率数据(Istanbul 格式) */
  coverage: any;
}

上报时机

  1. 定时上报:根据 reportInterval 配置定时上报(默认 30 秒)
  2. 页面关闭时:监听 beforeunload,使用 fetch keepalive 上报
  3. 页面隐藏时:监听 visibilitychange 事件,在页面隐藏时上报
  4. 手动上报:调用 report() 方法

注意事项

  1. 只在测试环境使用:代码插桩会增加代码体积和运行时开销,不要在生产环境启用
  2. Source Map 问题:如果你的构建工具(如 Webpack)对代码进行了二次编译,可能需要使用 coverage-source-map-trace-plugin 来修正源码偏移
  3. 浏览器兼容性:需要支持 fetch 和 keepalive 的现代浏览器
  4. CORS 问题:确保后端接口配置了正确的 CORS 头

调试

开启 debug: true 后,SDK 会在控制台输出详细日志:

init({
  // ...
  debug: true,
});

你会看到类似的日志:

[Coverage SDK] SDK 初始化成功 {...}
[Coverage SDK] 会话ID: 1234567890-abc123
[Coverage SDK] 定时上报已启动,间隔: 30000ms
[Coverage SDK] 开始采集覆盖率数据
[Coverage SDK] 准备上报数据: {...}
[Coverage SDK] 上报成功

License

MIT