基於Grunt&Mocha 搭建Nodejs自動化單元測試框架(含代碼覆蓋率統計)


Introduction

Grunt 是一個基於任務的JavaScript 世界的構建工具

Mocha 是具有豐富特性的 JavaScript 測試框架,可以運行在 Node.js 和瀏覽器中,使得異步測試更簡單更有趣。Mocha 可以持續運行測試,支持靈活又准確的報告,當映射到未捕獲異常時轉到正確的測試示例。

 

Prerequisite

nodejs項目文件目錄結構如下

├── config
├── controllers
├── models
├── lib
├── node_modules
├── test
├── tasks
│   ├── mochacli.js
│   ├── sonarRunner.js
│   └── mocha_istanbul.js    
│── package.json
└── Gruntfile.js
        

test 文件夾存放所有的單元測試*.js 文件

tasks 文件夾放的是一些給grunt 執行的task 文件

package.json 里用到的依賴如下

"devDependencies": {
    "chai": "^3.0.0",
    "chai-as-promised": "^5.1.0",
    "grunt": "^0.4.1",
    "grunt-config-dir": "^0.3.2",
    "grunt-mocha-cli": "^1.5.0",
    "grunt-mocha-istanbul": "^2.4.0",
    "grunt-sonar-runner": "^2.4.3",
    "istanbul": "^0.3.14",
    "load-grunt-tasks": "~0.2",
    "mocha": "^1.18.0",
    "sinon": "^1.15.4",
    "supertest": "^0.9.0"
  }

這些包的安裝都是通過命令 npm install xxx --save-dev 

 

Grunt task

Gruntfile.js 配置如下

'use strict';

module.exports = function (grunt) {

    // Load the project's grunt tasks from a directory
    require('grunt-config-dir')(grunt, {
        configDir: require('path').resolve('tasks')
    });

    // Register tasks
    grunt.registerTask('test', [ 'mochacli' ]);
    grunt.registerTask('coverage', [ 'mocha_istanbul:coverage','sonarRunner:analysis']);
};

 

Task - 'mochacli' 如下

'use strict';

module.exports = function mochacli(grunt) {
    // Load task
    grunt.loadNpmTasks('grunt-mocha-cli');

    // Options
    return {
        src: ['test/**/*.js'],
        options: {
            timeout: 6000,
            'check-leaks': true,
            ui: 'bdd',
            reporter: 'spec'
        }
    };
};

用這個插件來運行Mocha的測試。

 

Task - 'mocha_istanbul' 如下

'use strict';

module.exports = function clean(grunt) {
    // Load task
    grunt.loadNpmTasks('grunt-mocha-istanbul');

    // Options
    return {
            coverage: {
                src: 'test', // a folder works nicely
                options: {
                    coverage: true,
                    reportFormats: ['lcov','lcovonly'],
                    root: '.',
                    recursive: true
                }
              }
  };
};

istanbul這個插件是用來計算代碼覆蓋率的,並且可以生成lcov格式的report, 以便與下一個插件sonarRunner集成,展示報告

 

Task - 'sonarRunner.js' 如下

'use strict';

module.exports = function clean(grunt) {
    // Load task
    grunt.loadNpmTasks('grunt-sonar-runner');

    // Options
    return {
      analysis: {
        options: {
          debug: true,
          separator: '\n',
          sonar: {
            host: {
              url: 'http://10.101.46.20:9000'
            },
            jdbc: {
              url: 'jdbc:mysql://10.101.46.20:3306/sonar',
              username: 'sonar',
              password: 'sonar'
            },

            javascript: {
              lcov: {
                reportPath: 'coverage/lcov.info'
              }
            },

            projectKey: 'Demo:0.1.0',
            projectName: 'Demo project',
            projectVersion: '0.1.0',
            sources: ['controllers','models','lib'].join(','),
            language: 'js',
            sourceEncoding: 'UTF-8'
          }
        }
      }
    };
};

 

運行grunt test 示例結果如下 (其實有很多用例,這里為了好展示圖片,就run了一個)

 

運行grunt coverage 后

這里面兩個task, 運行完第一個mocha_istanbul:coverage后, 根目錄下會產生一個coverage目錄

└──coverage
    ├── coverage.json
    ├── lcov.info
    └── lcov-report
        ├── index.html
        ├── xxx
        └── xxx

lcov.info格式的文件是給Sonnar展示報告用的

打開lcov-report/index.html 如下圖

 

第二個插件是用來與Sonar集成的, 這幾個grunt命令我是放在jenkins里daily build后執行的

不知道為何Sonar 解析出來的代碼覆蓋率數字 與 istanbul插件算出來的 差距很大。。

 

Reference

Grunt: http://gruntjs.com/

Mocha: http://mochajs.org/

grunt-mocha-cli

grunt-mocha-istanbul

grunt-sonar-runner

 

感謝閱讀,如果您覺得本文的內容對您的學習有所幫助,您可以點擊右下方的推薦按鈕,您的鼓勵是我創作的動力。

##轉載注明出處:http://www.cnblogs.com/wade-xu/p/4710968.html 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM