博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
#单元测试#以karma+mocha+chai 为测试框架的Vue webpack项目(一)
阅读量:6900 次
发布时间:2019-06-27

本文共 6188 字,大约阅读时间需要 20 分钟。

目标:

  • 为已有的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配置文件(),再编写测试脚本,进行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【转至本文
  • 修改配置文件后,再次运行 #karma start     
终端运行过程: [user1@localhost webAdmin-web]$ karma startwebpack: wait until bundle finished:                            // 等待webpack打包绑定完成Hash: f11981cb4ab6cc3cc7caVersion: webpack 2.7.0Time: 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]  apptest/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/

         

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

         

  浏览器中:

 

修改错误:详见 

 

 

  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、

2、

3、

4、

 

转载于:https://www.cnblogs.com/vae860514/p/8289579.html

你可能感兴趣的文章
工作总结
查看>>
一个恶心的需求
查看>>
分类精度评价指标
查看>>
文件操作
查看>>
openssl编译时!遇见的问题
查看>>
Linux安全加固--精简启动项
查看>>
软件需求分析模板
查看>>
HDU - 5457 Hold Your Hand (Trie + 最小割)
查看>>
MySql 到 SQL Server(MSSQL)
查看>>
静态链表
查看>>
解决VS2005 VS2008 vs2010断点无效-源代码与原始版本不同
查看>>
NFS
查看>>
静电引发的悲剧
查看>>
在Angularjs中使用directive自定义指令实现attribute的继承
查看>>
新手学习编程的最佳方式是什么
查看>>
程序员零起步(四)——实习
查看>>
day6
查看>>
Aix下如何运行Java程序
查看>>
js简单总结
查看>>
隐马尔可夫HMM中viterbi算法
查看>>