• 选用 jest 做单元测试
    • 配置 eslint 的 jest 环境
    • 解决 jest 不支持 es module 的问题
    • test 目录下创建 [name].test.js(name 和 源码中的文件名保持一致) ``shell // 安装jest依赖 npm i -D jest // 使得支持es module` npm i -D rollup-jest
    1. package.json中设置
    2. ```shell
    3. "scripts":{
    4. "test": "jest",
    5. "test:c": "jest --coverage",
    6. },
    7. "jest": {
    8. "preset": "rollup-jest"
    9. }

    __test__文件下创建index.test.js

    1. /* eslint-disable no-undef */
    2. const { sum } = require('../src/index')
    3. test('sum success', () => {
    4. expect(sum(1, 2)).toBe(3)
    5. })

    src/index.js文件的内容修改为

    1. function sum() {
    2. let args = Array.from(arguments)
    3. return args.reduce((start, result) => {
    4. return start + result
    5. }, 0)
    6. }
    7. export { sum }

    执行 npm run test 进行测试
    image.png
    执行 npm run test:c 查看测试覆盖率
    image.png
    并且会在根目录生成一个converage目录
    image.png