首页 文章

代码覆盖Mocha

提问于
浏览
228

我正在使用Mocha来测试我的NodeJS应用程序 . 我无法弄清楚如何使用其代码覆盖功能 . 我试过谷歌搜索它,但没有找到任何适当的教程 . 请帮忙 .

3 回答

  • 343

    现在( 2018 )使用istanbul的首选方法是通过"state of the art command line interface" nyc .

    设置

    首先,将它安装在您的项目中

    npm i nyc --save-dev
    

    然后,如果你有一个基于npm的项目,只需更改package.json文件的 scripts 对象内的测试脚本,即可执行mocha测试的代码覆盖:

    {
      "scripts": {
        "test": "nyc --reporter=text mocha"
      }
    }
    

    现在运行测试

    npm test
    

    您将在测试输出后立即在控制台中看到这样的表格:

    自定义

    Html报告

    只是用

    nyc --reporter=html
    

    而不是 text . 现在它将在 ./coverage/index.html 内生成一份报告 .

    报告格式

    伊斯坦布尔支持各种报告格式 . 只需看看它的reports library就能找到对你最有用的东西 . 只需为您想要的每种格式添加 --reporter=REPORTER_NAME 选项 . 例如,用

    nyc --reporter=html --reporter=text
    

    你将拥有控制台和HTML报告 .

    不要使用npm test运行覆盖率

    只需在 package.json 中添加另一个脚本,并将 test 脚本仅包含您的测试运行器(例如mocha):

    {
      "scripts": {
        "test": "mocha",
        "test-with-coverage": "nyc --reporter=text mocha"
      }
    }
    

    现在运行此自定义脚本

    npm run test-with-coverage
    

    使用代码覆盖率运行测试 .

    如果代码覆盖率较低,则强制测试失败

    如果总代码覆盖率低于90%则失败:

    nyc --check-coverage --lines 90
    

    如果至少一个文件的代码覆盖率低于90%,则失败:

    nyc --check-coverage --lines 90 --per-file
    
  • 18

    你需要一个额外的库来代码覆盖,你将会被强大而简单的istanbul所震撼 . 在让mocha测试通过后,请尝试以下操作:

    npm install nyc
    

    现在,只需将命令nyc放在现有测试命令的前面,例如:

    {
      "scripts": {
        "test": "nyc mocha"
      }
    }
    
  • 68

    Blanket.js也很完美 .

    npm install --save-dev blanket

    在test / tests.js前面

    require('blanket')({
        pattern: function (filename) {
            return !/node_modules/.test(filename);
        }
    });
    

    mocha -R html-cov > coverage.html

相关问题