karma+jasmine前端單元測試
Q:為何要單元測試?
A:為了提升代碼的質量、減少bug、快速定位bug、減少調試時間。
本文主要采用karma+jasmine來進行簡單的單元測試。
0.生成一個項目package.json:
$ npm init -y
1.安裝必須依賴:
$ npm install karma --save
$ npm install karma-jasmine --save
$ npm install karma-chrome-launcher --save
$ npm install jasmine-core --save
$ sudo npm install karma-cli -g
$ npm install karma-coverage --save-dev
2.創(chuàng)建文件
在項目中創(chuàng)建一個js文件夾,在其中創(chuàng)建以下內容的js文件
// index.js
function test1(){
return 'abc';
}
function test2(){
return '333';
}
// jasmineTest.js
describe('TestFunction',function(){
it('測試test',function(){
expect('abc').toEqual(test1());
});
it('測試test2',function(){
expect('123').toEqual(test2());
});
});
3.生成karma.conf.js
在項目根目錄中使用karma init 生成一個測試配置文件:內容如下
// Karma configuration
// Generated on Mon Nov 07 2016 19:54:49 GMT+0800 (CST)
module.exports = function(config) {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: 'js',
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['jasmine'],
// list of files / patterns to load in the browser
files: ['*.js'
],
// list of files to exclude
exclude: [
],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {'js/*.js':'coverage'
},
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['progress','coverage'],
// 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: true,
// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
browsers: ['Chrome'],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: false,
// Concurrency level
// how many browser should be started simultaneous
concurrency: Infinity
})
}
4.開始測試:
$ karma start
5.測試結果:
在瀏覽器的console中可以看到結果,也可以在命令行中看到SUCCESS。
6.單元測試覆蓋率:
當我們在控制臺鍵入karma start的時候會生成一個coverage文件夾,點擊index.html文件,在瀏覽器中打開,可以查看到測試報表。