#单元测试#以karma+mocha+chai 为测试框架的Vue webpack项目(一)

目标:

  • 为已有的vue项目搭建 karma+mocha+chai 测试框架
  • 编写组件测试脚本
  • 测试运行通过
  • 抽出共通

 

一、初始化项目

    新建项目文件夹并克隆要测试的已有项目 webAdmin-web

     转到项目根目录,安装项目依赖:

#npm install

 谁安装失败就单独再安装它(如:chromedriver安装失败,#npm install chromedriver) 

 

二、搭建karma+mocha+chai测试环境

  1、安装插件

#npm install karma --save-dev
#npm install -g karma-cli
#npm install --save-dev mocha #npm install --save-dev karma-mocha #npm install --save-dev chai // 断言库 #npm install --save-dev karma-chai #npm install --save-dev sinon-chai #npm install --save-dev sinon #npm install --save-dev karma-sinon-chai #npm install --save-dev karma-webpack #npm install --save-dev karma-coverage #npm install --save-dev karma-spec-reporter #npm install --save-dev karma-sourcemap-loader #npm install --save-dev nib #npm install --save-dev opn #npm install --save-dev karma-chrome-launcher

 

  2、生成配置文件 karma.conf.js

     之前全局安装了karma-cli,便于引导我们生成karma.conf.js配置文件。

 #karma init

          配置文件已经自动生成,位置就在文件根目录。若用命令【#karma init 自定义配置名.conf.js】,则生成的配置文件名称就是“自定义配置名.conf.js”。

 

    3、在项目根目录下运行karma

        #karma start karma.conf.js

        运行结果:

       目前/test/unit/下还没有*specs.js文件,故而显示的结果是执行0错误0。

  

    4、编写简单的测试case 【正确顺序:先修改karma配置文件(转至本文 5),再编写测试脚本,进行karma测试】

  • 在/src 下新建测试代码文件夹 testSrc,新建测试文件add.js,文件结构如下:

            

  •  /src/testSrc/add.js 内容如下:    
  /**
   * 加法 
   * @param x 参数1
   * @param y 参数2
   */
  export function add (x, y) {
    return x + y
  }
  • 编写对应的测试脚本 /test/unit/specs/add.specs.js :
  import {add} from '@/testSrc/add.js'
  var expect = require('chai').expect

  describe('加法函数的测试', function() {
    it('1 加 1 应该等于 2', function() {
      expect(add(1,1)).to.be.equal(2)
    })
  })
  • 测试运行:#karma start
  • 测试结果:报错 —— import declarations may only appear at top level of a module

  • 原因分析:测试脚本没有被webpack打包,也可以说是karma没有配置webpack配置信息,所以karma start的时候不能直接用 import语法 。
  • 解决方法:修改karma配置文件 karma.conf.js【转至本文 5、修改karma配置文件
  • 修改配置文件后,再次运行 #karma start     
终端运行过程:

[user1@localhost webAdmin-web]$ karma start webpack: wait until bundle finished: // 等待webpack打包绑定完成 Hash: f11981cb4ab6cc3cc7ca Version: webpack 2.7.0 Time: 11959ms Asset Size Chunks Chunk Names static/img/401.089007e.gif 164 kB [emitted] static/img/404.a57b6f3.png 98.1 kB [emitted] 0.bundle.js 93.8 kB 0 [emitted] app 5.46 MB 1 [emitted] [big] app test/unit/specs/add.specs.js 216 kB 2 [emitted] test/unit/specs/add.specs.js

..... //非常长的一段文件解析过程

ERROR in ./test/unit/specs/add.specs.js                                                              // 错误信息

✘ http://eslint.org/docs/rules/no-undef 'describe' is not defined
test/unit/specs/add.specs.js:4:1
describe('加法函数的测试', function() {
^

✘ http://eslint.org/docs/rules/space-before-function-paren Missing space before function parentheses
test/unit/specs/add.specs.js:4:29
describe('加法函数的测试', function() {
^

✘ http://eslint.org/docs/rules/no-undef 'it' is not defined
test/unit/specs/add.specs.js:5:3
it('1 加 1 应该等于 2', function() {
^

✘ http://eslint.org/docs/rules/space-before-function-paren Missing space before function parentheses
test/unit/specs/add.specs.js:5:30
it('1 加 1 应该等于 2', function() {
^

✘ http://eslint.org/docs/rules/comma-spacing A space is required after ','
test/unit/specs/add.specs.js:6:17
expect(add(1,1)).to.be.equal(2)
^

✘ http://eslint.org/docs/rules/eol-last Newline required at end of file but not found
test/unit/specs/add.specs.js:8:3
})
^


✘ 6 problems (6 errors, 0 warnings)

 

webpack: Failed to compile.                                                        // webpack:编译失败

// 接下来是karma测试的结果,见下面的截图

  • 查看覆盖率报告文件 /test/unit/coverage/

         

    找到对应的报告文件,复制文件路径,在浏览器打开查看:

         

  浏览器中:

 

修改错误:详见 解决未安装unit测试和jest的Vue项目运行karma start时的错误

 

 

  5、修改karma配置文件    

     主要是在 karma.conf.js 中引入webpack配置、修改框架frameworks信息、预处理器、新增插件、修改reporters、新增coverageReporter(karma测试结果覆盖率报告文件)。修改后的配置文件如下:

// Karma configuration
// Generated on Mon Jan 15 2018 20:50:28 GMT+0800 (CST)

// 引入webpack配置
const webpackConfig = require('./build/webpack.base.conf');

module.exports = function(config) {
  config.set({
    // 引入webpack
     webpack: webpackConfig,

    // base path that will be used to resolve all patterns (eg. files, exclude)
    basePath: '',


    // frameworks to use -- 修改,增加'sinon-chai'
    // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
    frameworks: ['mocha', 'sinon-chai'],


    // 测试入口文件--测试脚本
    // list of files / patterns to load in the browser
    files: [
      'test/unit/**/*.specs.js'
    ],


    // list of files / patterns to exclude
    exclude: [
    ],


    // 预处理器--增加webpack、sourcemap、coverage
    // preprocess matching files before serving them to the browser
    // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
    preprocessors: {
      'test/unit/**/*.specs.js': ['webpack', 'sourcemap', 'coverage']
    },


    // 新增插件
    plugins: [
      'karma-webpack',
      'karma-sourcemap-loader',
      'karma-mocha',
      'karma-chai',
      'karma-sinon-chai',
      'karma-firefox-launcher',
      'karma-chrome-launcher',
      'karma-spec-reporter',
      'karma-coverage'
    ],

    // test results reporter to use
    // possible values: 'dots', 'progress'--新增spec、coverage
    // available reporters: https://npmjs.org/browse/keyword/karma-reporter
    reporters: ['spec', 'coverage', 'progress'],

    // 新增覆盖率报告
    coverageReporter: {
      // dir: './coverage',
      dir: './test/unit/coverage',
      reporters: [
        { type: 'html', subdir: 'report-html' },
        { type: 'lcov', subdir: '.' },
        { type: 'text-summary' }
      ]
    },

    // 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', 'Firefox'],


    // 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
  })
}

  

  6、抽出共通

 

--- 下一篇学习对组件进行测试。

  

资料:

1、karma官网/intro/installation【安装】

2、karma官网/intro/Configuration 【配置】

3、Vue.js 项目使用 Karma 做自动化UI测试小结 #58

4、测试框架 Mocha 实例教程

 

posted @ 2018-01-15 19:38  路过sayhi  阅读(831)  评论(0编辑  收藏  举报