1. 程式人生 > >前端自動化測試工具--使用karma進行javascript單元測試

前端自動化測試工具--使用karma進行javascript單元測試

前面我寫了一篇部落格是《前端自動化測試工具PhantomJS+CasperJS結合使用教程》其中使用CasperJS不僅可以進行單元測試,還可以進行瀏覽器測試,是個很不錯的工具,今天介紹的工具是Karma+Jasmine+PhantomJS組合的前端javascript單元測試工具。

1.介紹

Karma是由Google團隊開發的一套前端測試執行框架,karma會啟動一個web伺服器,將js原始碼和測試指令碼放到PhantomJS或者Chrome上執行。

2.安裝

  • 包管理package.json
npm init

一路回車下去即可
- 在專案中安裝karma包

npm
i karma --save-dev
  • karma初始化
karma init

按照下面的選擇好

E:\javascript\auto-test\karma-demo>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. > src/**/*.js > test/**/*.js 14 10 2016 10:49:43.958:WARN [init]: There is no file matching this pattern. > 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. > yes Config file generated at "E:\javascript\auto-test\karma-demo\karma.conf.js".

上圖是選項的示例,這裡使用jasmine測試框架,PhantomJS作為程式碼執行的環境(也可以選擇其他瀏覽器作為執行環境,比如Chrome,IE等)。最後在專案中生成karma.conf.js檔案
- 安裝jasmine-core

npm i jasmine-core --save-dev

3.demo1–ES5

目錄結構

karma-example
    ├──  src
         ├──  index.js
    ├──  test
    ├──  package.json

原始碼:src–index.js

function isNum(num) {
    if (typeof num === 'number') {
        return true;
    } else {
        return false;
    }
}

測試:test–index.js

describe('index.js: ', function() {
  it('isNum() should work fine.', function() {
    expect(isNum(1)).toBe(true)
    expect(isNum('1')).toBe(false)
  })
})

執行,執行命令

karma start

命令列結果

14 10 2016 10:56:13.038:WARN [karma]: No captured browser, open http://localhost:9876/
14 10 2016 10:56:13.067:INFO [karma]: Karma v1.3.0 server started at http://localhost:9876/
14 10 2016 10:56:13.101:INFO [launcher]: Launching browser PhantomJS with unlimited concurrency
14 10 2016 10:56:13.119:INFO [launcher]: Starting browser PhantomJS
14 10 2016 10:56:16.207:INFO [PhantomJS 2.1.1 (Windows 8 0.0.0)]: Connected on socket /#JoOdYxAeCS4xvhHHAAAA with id 87859111
PhantomJS 2.1.1 (Windows 8 0.0.0): Executed 1 of 1 SUCCESS (0.009 secs / 0.004 secs)

4.demo2-ES6

安裝使用Webpack+Babel

npm i  karma-webpack --save-dev
npm i  babel-loader babel-core babel-preset-es2015 --save-dev

原始碼src–index2.js

function isNum(num) {
  if (typeof num === 'number') {
    return true;
  } else {
    return false;
  }
}

export {isNum};
// export default isNum;

測試test–index2.js

import {isNum} from '../src/index2';
// import isNum from '../src/index2';

describe('index2.js:', () => {
  it('isNum() should work fine.', () => {
    expect(isNum(1)).toBe(true);
    expect(isNum('1')).toBe(false);
  });
});

修改配置檔案karma.conf.js

config.set({
        basePath: '',
        frameworks: ['jasmine'],
        //修改
        files: [
            // 'src/**/*.js',
            'test/**/*.js'
        ],
        exclude: [],
        preprocessors: {
            'test/**/*.js': ['webpack', 'coverage'] //新增
            //coverage為覆蓋率測試,這裡不再介紹
        },
        reporters: ['progress', 'coverage'],
        // 新增--覆蓋率測試
        coverageReporter: {
            type: 'html',
            dir: 'coverage/'
        },
        port: 9876,
        colors: true,
        logLevel: config.LOG_INFO,
        autoWatch: true,
        browsers: ['PhantomJS'],
        singleRun: false,
        concurrency: Infinity,
        //新增
        webpack: {
            module: {
                loaders: [{
                    test: /\.js$/,
                    loader: 'babel',
                    exclude: /node_modules/,
                    query: {
                        presets: ['es2015']
                    }
                }]
            }
        }
    })