美文网首页
前端单元测试(一)karma

前端单元测试(一)karma

作者: liajoy | 来源:发表于2017-03-12 16:58 被阅读0次

    一直很想做单元测试,也在尝试着开始写,但是由于项目采用vue书写,一是开始写项目的时候没有编写单元测试的意识,导致后期编写有些麻烦,二是新需求层出不穷,没有精力进行编写。但是随着vue-cli更新到2.8,推出了一个vue build的功能后,对于vue的测试变得简单起来。
    先讲讲单元测试的工具:karma和mocha

    karma

    karma是一个测试管理工具,可以很容易和Jasmine、Mocha等市面上常用的测试框架打通,通过其插件可以快速集成到各种环境中。例如:本地环境、持续集成环境。

    安装

    npm install karma-cli -g
    npm install karma --save-dev
    npm install karma-mocha --save-dev
    npm install karma-chai --save-dev
    

    这里使用mocha作为测试库,chai作为断言库。
    使用jasmine的话,可以不引断言库。

    初始化

    使用cmd或者shell(使用git bash会报错)输入karma init后选择选项。

    Which testing framework do you want to use ? 
    Press tab to list possible options. Enter to move to the next question.
    > mocha
    
    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.
    > Chrome
    
    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. > "test/**/*.spec.js" 
    >
    
    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
    

    之后karma会生成一个karma.conf.js,大体上就是我们之前的选项。
    使用mocha,需要在framework中加入chai,否则要在测试js中手动引入。
    在浏览器这里,需要install相应的launcher,如karma-chrome-launcher,一般用phantomjs就行了。当然,在可视浏览器中可以使用部分es6功能,所以只是简单测试,使用它们也行。

    //karma.conf.js
    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: ['mocha','chai'],
    
    
        // list of files / patterns to load in the browser
        files: ['*.js'],
    
    
        // list of files to exclude
        exclude: ['karma.config.js'],
    
    
        // preprocess matching files before serving them to the browser
        // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
        preprocessors: {
        },
    
    
        // 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
      })
    }
    

    开始

    配置完后,就可以开始测试了。项目目录如下:

    项目目录

    index和index-spec随便取啥都可以,作为全局环境的引入,karma会根据函数名进行判断,但是为了规范,尽量后缀名为test或者spec。
    我们实现一个简单的对hello的测试。

    //hello.js
    function hello(name){
        return 'hello ' + name
    }
    
    //hello.spec.js
    describe('this is hello test',function(){
        it('hello',function(){
            expect(hello('world')).to.be.equal('hello world')
            expect(hello('gay')).to.be.equal('hello gay')
        })
    })
    

    接着运行 karma start。你会发现karma打开了谷歌浏览器,并且还有一个DEBUG的按钮,同时命令行中也出现了测试的结果。
    如果测试未通过,DEBUG页面中的控制台将会提示错误信息。

    配合webpack

    首先安装webpack、karma-webpack以及babel。

    npm install webpack karma-webpack --save-dev
    npm install babel-loader babel-core babel-preset-es2015 --save-dev
    
    // karma.config.js
    module.exports = function(config) {
      config.set({
        // ......
        preprocessors: {
          '*.js': ['webpack']
        },
        webpack: {
          module: {
            loaders: [{
              test: /\.js$/,
              exclude: /node_modules/,
              loader: "babel-loader",
              query: {
                presets: ["es2015"],
              }
            }]
          }
        },
        // ......
      })
    }
    

    再次运行,可以看到在启动浏览器之前,所有代码都经过了webpack的打包,因此需要将被测试代码引入测试代码中才行。

    //hello.js
    export default name => 'hello ' + name
    
    //hello.spec.js
    import hello from "./hello.js";
    //...
    

    接下去的拓展,就和平时配置webpack一样。如果我需要对.vue文件或者Vue进行测试,通过安装vue-loader,配置webpack的loader。就可以实现vue官方文档的简单事例。

    测试覆盖率

    npm install karma-coverage --save-dev
    
    //karma.config.js
    module.exports = function(config) {
        config.set({
        //...
            preprocessors: {
                '*.spec.js': ['webpack','coverage']
            },
            reporters: ['progress','coverage'],
            webpack: {
                module: {
                    loaders: [
                  //...  
                  ,{
                        test: /\.vue$/,
                        loader: "vue-loader"
                    }]
                }
            },
        })
    }
    

    运行后在文件目录中会自动创建一个coverage的文件夹,里边包含了覆盖率的指数。

    Paste_Image.png

    打开一看,覆盖率好低,代码行数也增多不少,点开文件会发现这些代码是打包过后的代码,因此覆盖率降低不少。

    npm install babel-plugin-istanbul --save-dev
    
    karma.config.js
    loaders: [{
                        test: /\.js$/,
                        exclude: /node_modules/,
                        loader: "babel-loader",
                        query: {
                            presets: ["es2015"],
                            plugins: ['istanbul']
                        }
                    },
    

    再次运行发现,覆盖率已经是你期盼的值了。

    相关文章

      网友评论

          本文标题:前端单元测试(一)karma

          本文链接:https://www.haomeiwen.com/subject/duytnttx.html