karma與webpack結合

來源:互聯網
上載者:User

標籤:

一、必備外掛程式

1.babel:es6的文法支援

2.karma:測試架構

3.jasmine:斷言架構

4.webpack:打包工具

5.karma-webpack:karma調用webpack打包介面的外掛程式

二、實現步驟1.通過npm安裝上述必備的外掛程式包2.建立webpack.test.config.js檔案,此檔案的配置用於單元測試
var path = require(‘path‘);var webpack = require(‘webpack‘);module.exports={    module:{        loaders:[{            test:/\.js$/,            loader:‘babel‘,            query:{                presets:[‘es2015‘]            },            exclude:[               path.resolve( __dirname, ‘../test‘ ), path.resolve( __dirname, ‘../node_modules‘ )            ]        }]    }};

注意:

1.此配置參數中沒有entry、output兩個節點的配置,打包的輸入和輸出karma會指定

3. 通過karma init命令建立karma.conf.js設定檔

此檔案建立好之後,手動添加對webpack.test.config.js檔案的引用,且需要增加如下節點:

1.webpack:設定webpack相關配置參數,也就是匯入的webpack.test.config.js的對象

2.webpackMiddleware:設定webpack-dev-middleware(實現webpack的打包,但可以控制輸入和輸出)外掛程式的相關參數

3.preprocessors:增加對webpack引用。

var webpackConfig = require(‘./webpack.test.config‘);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: [        ‘../test/index.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: {      ‘../test/index.js‘:[‘webpack‘]    },    // 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: 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,    webpack: webpackConfig,    webpackMiddleware:{      noInfo:false    }  })}
 

注意:配置的files與preprocessors節點都是指向單元測試的入口檔案(test/index.js)

4.建立需要測試的源碼與單元測試檔案

1.src/cache/index.js:cache模組匯出介面,本次只匯出的memoryCache.js,代碼如下:

export { default as MemoryCache } from ‘./memoryCache‘;

2.src/cache/memoryCache.js:實現快取資料的操作,也是需要單元測試的類,代碼如下:

export default class MemoryCache extends abCache{    constructor( limit ){        super( limit );        this._map = [];    }}var p = MemoryCache.prototype;p.push = function(key, item){    var entry = {        key: key,        value: item    };    this._map.push(entry);};p.get = function(key,ruturnEntry){    for(let item of this._map){        if(item.key == key){            return ruturnEntry ? item.value : item;        }    }    return null;};p.remove = function(key){    for(let index in this._map){        if(this._map[index].key == key){            this._map.splice(index,1);            return;        }    }}

 

3.test/cache/memoryCacheTest.js:單元測試用例類

var _memory = require(‘../../src/cache/index.js‘).MemoryCache;describe(‘memoryCache test‘,function(){    var _memeoryCache;    _memeoryCache = new _memory();    beforeEach(function(){ //每運行一個it時,之前執行    });    it(‘push‘,function(){        var foo = {"name":"foo.Name"};        _memeoryCache.push("foo",foo);        var _destFoo = _memeoryCache.get(‘foo‘,true);        expect(_destFoo).toBe(foo);    });    it(‘get‘, function(){       expect(_memeoryCache.get(‘foo‘,true)).not.toBeNull();    });    it(‘remove‘,function(){        _memeoryCache.remove(‘foo‘);        expect(_memeoryCache.get(‘foo‘)).toBeNull();    });});

 

4.test/index.js:單元測試的入口檔案

require(‘./cache/memoryCahceTest.js‘);

 

 

5. karma start運行單元測試即可。

karma與webpack結合

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.