搭建基于Mocha+Webpack2+Chai+ES6前端单元测试

发表于:2017-7-13 11:37

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:未知    来源:51Testing软件测试网采编

  现在如果写某些类库的话,非常注重单元测试,从而确保发版质量。大概测试框架也有很多,这里介绍比较常用的 前端测试框架技术选型。
  安装 Karma
 npm install -g karma-cli 
  然后使用 karma 初始化配置:
  karmainit
    如果提醒,安装依赖,你只需输入:
 npm install karma --save-dev 
  然后再执行一次就好,系统会提醒你进行一些输入操作,你可以直接跳过。这个时候程序会自动创建 karma.conf.js 。
  基本内容是:
 // Karma configuration
  // Generated on Wed Jul 12 2017 18:29:58 GMT+0800 (CST)
  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: [
      ],
      // 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 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
    })
  }
  其中 files 是指定测试的文件规则,比如 test/**/*.test.js表示运行 test 目录下所有 带有 test.js 后缀的文件。
  framework 则表示需要引用的框架,比如 jasmine 或者 mocha。
  preprocessors 表示 在浏览器进行测试前你需要对文件的一些预处理。
  我们后边会贴出完整的 karma.conf.js .
  安装webpack 和 babel
  npm install webpack babel-polyfill babel-preset-stage-2 babel-plugin-transform-runtime babel-loader babel-core babel-preset-env babel-istanbul --save-dev 
  编辑 .babelrc 确保我们的源码可以被编译成正确的浏览器支持的 ES5的代码
  {
    "presets": [
      ["env", { "modules": false }],
      "stage-2"
    ],
    "plugins": ["transform-runtime"],
    "comments": false,
    "env": {
      "test": {
        "presets": ["env", "stage-2"],
        "plugins": [ "istanbul" ]
      }
    }
  }
  这个时候我们还需要安装 karam 相关的插件
  npm install karma-webpack karma-sourcemap-loader --save-dev  
  安装 mocha 和 chai
  这个时候我们需要安装 mocha ,mocha 是一款功能丰富的javascript单元测试框架,它既可以运行在nodejs环境中,也可以运行在浏览器环境中。
  npm install mocha --save-dev 
  除了安装 mocha 外我们还需要安装 karma-mocha 插件
  npm install karma-mocha --save-dev 
  除了 mocha 外,我们需要安装 chai。 chai是一套TDD(测试驱动开发)/BDD(行为驱动开发)的断言框架。
  expect(foo).to.not.equal('bar');  
  expect(goodFn).to.not.throw(Error);  
  expect({ foo: 'baz' }).to.have.property('foo')  
    .and.not.equal('bar');

  npm install chai karma-chai --save-dev 
  除此之外,我们还需要确定我们测试的浏览器比如 Chrome 或者 PhantomJS等。
  npm install karma-chrome-launcher --save-dev 
  这个时候我们的karma 配置文件 karma.conf.js 的内容应该修改为
  const webpack = require("webpack");  
  const path = require('path');
  module.exports = function(config) {  
      config.set({
          files: [
              '../node_modules/babel-polyfill/dist/polyfill.min.js',
              './test/**/*.test.js'
          ],
          exclude: ['**/node_modules/**/*.test.js'],
          frameworks: ['mocha', 'chai'],
          logLevel: config.LOG_INFO, //config.LOG_DISABLE, // config.LOG_INFO
          singleRun: true,
          preprocessors: {
              './test/**/*.test.js': ['webpack']
          },
          // reporters: ['mocha'],
          webpack: {
              module: {
                  // devtool: 'inline-source-map',
                  loaders: [
                      {
                          test: /\.js$/,
                          loader: 'babel-loader',
                          exclude: /(node_modules|bower_components)/,
                      },
                  ]
              }
          },
          webpackServer: {
              noInfo: true
          },
          plugins: [
              "karma-webpack",
              "karma-mocha",
              "karma-chai",
              "karma-chrome-launcher",
              "karma-sourcemap-loader"
          ],
          browsers: ['Chrome'], // ['Chrome']
          concurrency: Infinity
      });
  };
  接下来我们修改 package.json 里的 scripts 脚本的 内容
   "test": "karma start test/karma.conf.js",
  这个时候输入 npm run test 就能查看正确的测试了。

  如果你需要引入 DOM 的操作,你需要安装 mocha-jsdom,这样你可以实现对 DOM 节点的操作和判断。
《2023软件测试行业现状调查报告》独家发布~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号