karma+jasmine前端單元測(cè)試
Q:為何要單元測(cè)試?
A:為了提升代碼的質(zhì)量、減少bug、快速定位bug、減少調(diào)試時(shí)間。
本文主要采用karma+jasmine來(lái)進(jìn)行簡(jiǎn)單的單元測(cè)試。
0.生成一個(gè)項(xiàng)目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)建文件
在項(xiàng)目中創(chuàng)建一個(gè)js文件夾,在其中創(chuàng)建以下內(nèi)容的js文件
// index.js
function test1(){
return 'abc';
}
function test2(){
return '333';
}
// jasmineTest.js
describe('TestFunction',function(){
it('測(cè)試test',function(){
expect('abc').toEqual(test1());
});
it('測(cè)試test2',function(){
expect('123').toEqual(test2());
});
});
3.生成karma.conf.js
在項(xiàng)目根目錄中使用karma init 生成一個(gè)測(cè)試配置文件:內(nèi)容如下
// 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.開(kāi)始測(cè)試:
$ karma start
5.測(cè)試結(jié)果:
在瀏覽器的console中可以看到結(jié)果,也可以在命令行中看到SUCCESS。
6.單元測(cè)試覆蓋率:
當(dāng)我們?cè)诳刂婆_(tái)鍵入karma start的時(shí)候會(huì)生成一個(gè)coverage文件夾,點(diǎn)擊index.html文件,在瀏覽器中打開(kāi),可以查看到測(cè)試報(bào)表。