完善自己的npm包

219 阅读2分钟

几天前简单的创建了一个npm包,今天对它进行完善一下,主要用了jestcoveralls插件,增加GitHub徽标等,由于第一次使用,记录一下,加深印象。

image.png

增加几个常用函数

向其中增加了一下常用的方法,下面列出几个,其余的记录在文档中 hxc1216.github.io/(文档有些瑕疵,点击左侧菜单后需要刷新页面才能正常显示)

// 随机获取十六进制颜色
const color = getColor16()
console.log(color) // #7328ae

// 下划线命名转驼峰
const str = "get_img_list"
const result = underToHump(str)
console.log(result) // #getImgList

// 解析URL参数
const url = "https://example.com/search?q=apple&filter=red&filter=round";
const query = getQuery(url)
console.log(query) // {q:"apple",filter:["red","round"]}

增加测试用例

1.安装jest插件

npm i --save-dev jest

2.package.json 配置命令

{
    scripts:{
        ...
        "jest": "jest"
    }
}

3.写测试用例

在项目根目录创建一个dist文件夹,在其中写测试用例,列举其中一个(这个是gpt写的...) 引入的话需要引入打包后的文件

const { getQuery } = require("../dist/utilx.min.cjs.js");

describe("getQuery", () => {
  test("getQuery should extract query parameters from url string", () => {
    const url = "https://example.com/search?q=apple&category=fruit&sort=price";
    const query = getQuery(url);

    expect(query).toEqual({
      q: "apple",
      category: "fruit",
      sort: "price",
    });
  });

  test("getQuery should handle url string without query parameters", () => {
    const url = "https://example.com";
    const query = getQuery(url);

    expect(query).toEqual({});
  });

  test("getQuery should handle url string with single query parameter", () => {
    const url = "https://example.com/search?q=apple";
    const query = getQuery(url);

    expect(query).toEqual({
      q: "apple",
    });
  });

  test("getQuery should handle url string with multiple parameters of the same name", () => {
    const url = "https://example.com/search?q=apple&filter=red&filter=round";
    const query = getQuery(url);

    expect(query).toEqual({
      q: "apple",
      filter: ["red", "round"],
    });
  });
});

4.运行测试

npm run jest

出现如下信息,测试用例全部通过 image.png

5.上传测试覆盖率

我使用的是 coverallsgithub actions ,下面是一些配置,首先安装 coveralls

npm i coveralls --save-dev

接着去 coveralls官网,使用github账号登录并关联自己的项目,在setting中找到REPO TOKEN,复制下来, 在项目根目录创建 .coveralls.yml 文件,内容如下,repo_token改为刚刚复制的token

service_name: github
repo_token: <your_repo_token>

github actions中创建一个新的workflow,内容如下

name: CI
on: [push]

jobs:
  build:

    runs-on: ubuntu-latest

    strategy:
      matrix:
        node-version: [16.x]

    steps:
    - uses: actions/checkout@v2
    - name: Use Node.js ${{ matrix.node-version }}
      uses: actions/setup-node@v2
      with:
        node-version: ${{ matrix.node-version }}
    - run: npm ci
    - run: npm test

至此,配置完成,提交代码时就会触发这个actionimage.png

6.添加徽标

测试覆盖率上传完成,接下来就可以添加徽标了,去到 Shields搜索 caoverage,找到 Coveralls branch,按照提示输入 github名字和项目名字

image.png 点击下面蓝色按钮就可以复制图片地址,在项目的 README.md 添加如下

[![coverage Status](https://img.shields.io/coverallsCoverage/github/hxc1216/util-xx?branch=dev)](https://img.shields.io/coverallsCoverage/github/hxc1216/util-xx?branch=dev)

提交代码,就可以看到徽标了

image.png