.Karma+Jasmine+karma-coverage


單元測試(模塊測試)是開發者編寫的一小段代碼,用於檢驗被測代碼的一個很小的、很明確的功能是否正確。一般而言,一個單元測試是用於判斷某個特定條件(或者場景)下某個特定函數的行爲。
html

Karma是一個基於Node.js的JavaScript測試執行過程管理工具( Test Runner ).。該工具可用於測試全部主流Web瀏覽器, 也可集成到CI ( Continuous integration ) 工具, 也可和其餘代碼編輯器一塊兒使用.。這個測試工具的一個強大特性就是, 它能夠監控(Watch)文件的變化, 而後自行執行。

jasmine 是一個行爲驅動開發(TDD)測試框架, 一個js測試框架,它不依賴於瀏覽器、dom或其餘js框架。具體語法參照:官方api
git

1.1 使用 Karma 對代碼進行單元測試,首先須要安裝一系列的相關插件。

建立fetest的文件夾,並進入github

安裝karma
web

npm install -g karma-cli複製代碼
npm install karma --save-dev複製代碼

安裝各類相關的插件npm

npm install karma-jasmine karma-phantomjs-launcher jasmine-core --save-dev 複製代碼

初始化,總體的配置選項以下:api

 

 

 

 

karma init 複製代碼
Which testing framework do you want to use ? Press tab to list possible options. Enter to move to the next question. > jasmine  Do you want to use Require.js ? This will add Require.js plugin. Press tab to list possible options. Enter to move to the next question. > no  Do you want to capture any browsers automatically ? Press tab to list possible options. Enter empty string to move to the next question. > PhantomJS > What is the location of your source and test files ? You can use glob patterns, eg. "js/*.js" or "test/**/*Spec.js". Enter empty string to move to the next question. >  Should any of the files included by the previous patterns be excluded ? You can use glob patterns, eg. "**/*.swp". Enter empty string to move to the next question. >  Do you want Karma to watch all the files and run the tests on change ? Press tab to list possible options. > no複製代碼

啓動karma瀏覽器

 

 

 

 

karma start複製代碼

出現一下界面表明成功,可進行下一步操做,第一次須要安裝phantomjsbash

 

 

 

 

npm install -g phantomjs複製代碼


初始化完成以後,會在咱們的項目中生成一個 karma.conf.js 文件,這個文件就是 Karma 的配置文件。框架

// Karma configuration // Generated on Sat Jun 02 2018 11:06:15 GMT+0800 (中國標準時間)  module.exports = function(config) {   config.set({      // base path that will be used to resolve all patterns (eg. files, exclude)     basePath: '',       // frameworks to use     // available frameworks: https://npmjs.org/browse/keyword/karma-adapter     frameworks: ['jasmine'], //使用何種斷言庫       // list of files / patterns to load in the browser     files: [        './unit/**/*.js',     //被測試的代碼路徑        './unit/**/*.spec.js' //測試代碼路徑     ],       // list of files / patterns to exclude     exclude: [     ],       // preprocess matching files before serving them to the browser     // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor     preprocessors: {     },       // test results reporter to use     // possible values: 'dots', 'progress'     // available reporters: https://npmjs.org/browse/keyword/karma-reporter     reporters: ['progress'],      // web server port     port: 9876,       // enable / disable colors in the output (reporters and logs)     colors: true,       // level of logging     // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG     logLevel: config.LOG_INFO,       // enable / disable watching file and executing tests whenever any file changes     autoWatch: false,       // start these browsers     // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher     browsers: ['PhantomJS'],       // Continuous Integration mode     // if true, Karma captures browsers, runs the tests and exits     singleRun: true,//執行完是否退出      // Concurrency level     // how many browser should be started simultaneous     concurrency: Infinity   }) }複製代碼

建立unit文件夾,並建立index.js、index.spec.jsdom

index.js

function add (num){     if(num == 1){         return 1;     }else{         return num+1;     }  }複製代碼

index.spec.js

describe("測試簡單基本函數", function() {     it("+1測試", function() {         expect(add(1)).toBe(1);         expect(add(2)).toBe(5);     }); });複製代碼

啓動karma

 

 

 

 

karma start複製代碼

成功了一個,錯誤一個。

1.2 使用 karma-coverage測試代碼覆蓋率

安裝karma-coverage

 

 

 

 

npm install karma-coverage --save-dev複製代碼

建立一個docs文件夾,用來存放生成的的測試文件,配置 karma.conf.js 文件:

// Karma configuration // Generated on Sat Jun 02 2018 19:49:27 GMT+0800 (中國標準時間)  module.exports = function(config) {   config.set({      // base path that will be used to resolve all patterns (eg. files, exclude)     basePath: '',       // frameworks to use     // available frameworks: https://npmjs.org/browse/keyword/karma-adapter     frameworks: ['jasmine'],       // list of files / patterns to load in the browser     files: [         './unit/**/*.js',         './unit/**/*.spec.js'     ],       // list of files / patterns to exclude     exclude: [     ],       // preprocess matching files before serving them to the browser     // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor     preprocessors: {         'unit/**/*.js': ['coverage']//對那些文件生成代碼覆蓋率檢查      },       // test results reporter to use     // possible values: 'dots', 'progress'     // available reporters: https://npmjs.org/browse/keyword/karma-reporter      reporters: ['progress','coverage'],//添加'coverage'      coverageReporter: {           type : 'html',           //生成html頁面           dir : './docs/coverage/' //存放html頁面位置     },      // web server port     port: 9876,       // enable / disable colors in the output (reporters and logs)     colors: true,       // level of logging     // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG     logLevel: config.LOG_INFO,       // enable / disable watching file and executing tests whenever any file changes     autoWatch: false,       // start these browsers     // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher     browsers: ['PhantomJS'],       // Continuous Integration mode     // if true, Karma captures browsers, runs the tests and exits     singleRun: true,      // Concurrency level     // how many browser should be started simultaneous     concurrency: Infinity   }) } 複製代碼

啓動karma

 

 

 

 

karma start複製代碼

會在docs中生成一個coverage文件夾,裏面有生成的測試代碼覆蓋率的可視化html頁面。


打開index.html


修改index.spec.js

describe("測試簡單基本函數", function() {     it("+1測試", function() {         expect(add(1)).toBe(1);     }); });複製代碼
karma start複製代碼

本站公眾號
   歡迎關注本站公眾號,獲取更多信息