karma与webpack结合

一、必备插件

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运行单元测试即可。

时间: 2024-10-11 11:17:31

karma与webpack结合的相关文章

Rails 5 Test Prescriptions 第10章 Unit_Testing JavaScript(新工具,learn曲线太陡峭,pass)

对Js的单元测试是一个大的题目.作者认为Ruby的相关测试工具比Js的测试工具更灵活 大多数Js代码最终是关于响应用户的行为和改变DOM中的元素 没有什么javascript的知识点.前两节用了几个新的测试工具,和大量配置,暂时pass. setup js Unit-tests writing a Sample test Tdd in Js jasmine matchers testing ajax calls using testdouble.js connecting the js to t

[Webpack 2] Use Karma for Unit Testing with Webpack

When writing tests run by Karma for an application that’s bundled with webpack, it’s easiest to integrate webpack and Karma directly together. In this lesson we’ll see how to utilize the karma-webpack plugin and reuse our existing webpack configurati

Vue.js——webpack

Vue.js——60分钟webpack项目模板快速入门 browserify是一个 CommonJS风格的模块管理和打包工具,上一篇我们简单地介绍了Vue.js官方基于browserify构筑的一套开发模板.webpack提供了和browserify类似的功能,在前端资源管理这方面,它提供了更加出色的功能.官方基于webpack提供了两种项目模板,分别是vue-webpack-simple模板和vue-webpack模板,今天我们将介绍官方提供的这两种项目模板,并用vue-webpack-sim

45.使用webpack,react,redux搭俩个界面

整理好写 { "private": true, "version": "0.0.1", "description": "YOUR DESCRIPTION - Generated by generator-react-webpack", "main": "", "scripts": { "clean": "rimraf

vue-cli&webpack&arcgis API For JS的天坑之路(一)

写在前面的话(背景交代) 最近参加esri比赛,但是又想趁机接触前端最新的一些框架和技术,所以,毅然决然的踏上了这个天坑之路.我现在只是成功的把地图渲染出来了,所以,我也不知道会不会有天坑二的出现. gituhb项目地址 新建vue-cli工程 如何用vue-cli + webpack构建一个工程,网上一大堆的代码,我就不赘述了.比如这个就是很好地入门文章,先要做的还是要把vue-cli和webpack的模块划分好,框架搭建好,然后才是我要说的,地图部分. 如何在vue-cli,webpack中

[Webpack 2] Add Code Coverage to tests in a Webpack project

How much of your code runs during unit testing is an extremely valuable metric to track. Utilizing code the karma-coverage plugin and babel-plugin-__coverage__ plugin, we can get an accurate measure of how well we’re covering the files that we are te

[Webpack 2] Intro to the Production Webpack Course

There are several lessons that will build on top of this project. It is a fairly standard, small webpack bundled project. In this lesson we’ll explore the project a bit so you’re familiar with how things are set up for future lessons. In Webpack 2, t

Webpack: 为Web开发而生的模块管理器[转]

Webpack: 为Web开发而生的模块管理器 原文地址:http://hanjianwei.com/2014/09/10/webpack-package-manager-for-web/ 10 Sep 2014 对于开发人员而言,好的包管理器可以让工作事半功倍.现在流行的编程语言大多有自己的包管理系统.近年来,Web开发越来越火,其开发工具也随之越来越好用了,而Webpack就是一款专为Web开发设计的包管理器.它能够很好地管理.打包Web开发中所用到的HTML.Javascript.CSS以

使用Karma 来进行 JavaScript 测试

最近接触了一些新的前端开发知识,主要是利用AngularJS做single page application.我也借这个机会,花了几天时间了解了如何对javascript进行测试. 这里将介绍一些使用到的模块及如何进行安装并测试. 技术要求: 熟悉JavaScript 有NodeJS的一些基础 词汇: NodeJS: NPM: NodeJS package manager,即nodejs的包管理器 SPA: Single Page Application,即单页面 相关模块 先大概说罗列一下需要