karma+jasmine前端單元測試

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文件,在瀏覽器中打開,可以查看到測試報表。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容