webpack+angular的项目SEED(下)

jopen 8年前

webpack+angular的项目SEED(上) 介绍了项目的构建生产和热编译显示。

介绍

这里就主要来讲测试,敏捷开发好多公司都在做,敏捷开发有许多种方法,但不管采用那一种方法,测试都是必须的,验证代码,验证功能,及时的反馈,及时的修复是保证敏捷开发的基础。所以自动化测试,才能保证开发在快速中仍然可以维护的很好,不会带来新的问题和代码质量问题。

单元测试

karma 可以同时对多个浏览器做单元测试,测试兼顾代码的兼容性。但是karma不包含断言库,所以还需要断言库,在这里我用了mocha+chai而不是Jasmine的。至于为什么说实话我也是刚刚接触自动化测试。没有依赖性,所以就晚上大概了解了下,选mocha主要因为他可扩展性和异步测试的能力。对比可以查看 这篇文章 ,然后由于用到了ES6所以在测试前需要吧代码编译,所以用到了karma-webpack和karma-sourcemap-loader这两个帮助定位代码位置。最后就是karma-mocha-reporter这个帮助我更加清晰的查看测试报告。

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: ['app/**/*Spec.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: {'app/**/*Spec.js': ['webpack', 'sourcemap']},              // test results reporter to use          // possible values: 'dots', 'progress'          // available reporters: https://npmjs.org/browse/keyword/karma-reporter          reporters: ['mocha'],              // 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: {              devtool: 'inline-source-map',              module: {                  loaders: [                      {test: /\.js/, exclude: [/app\/lib/, /node_modules/], loader: 'babel'},                      {test: /\.html/, loader: 'raw'},                      {test: /\.styl$/, loader: 'style!css!stylus'},                      {test: /\.css$/, loader: 'style!css'}                  ]              }          },          webpackServer: {              noInfo: true // prevent console spamming when running in Karma!          },          plugins: [              'karma-chrome-launcher',              'karma-chai',              'karma-mocha',              'karma-webpack',              'karma-sourcemap-loader',              'karma-mocha-reporter'          ]      })  };

KARMA的主要测试配置就在这里了。KARMA最大的好处就是能监视代码修改,实时的帮你测试代码问题。在开发的同时就能知道会不会有太大的问题。很好的管控了代码。

对了还有一个问题就是对angularJS的测试需要'angular-mocks'的搭配,可以帮你测试module,controller里面的内容。

navbar.js

let navbar = angular.module('navbar', []);  navbar.controller('navbarCtrl', ['$scope', function ($scope) {      $scope.links = ['home', 'about'];  }]);    navbar.directive('navbar', function () {      return {          restrict: 'AE',          templateUrl: '/widgets/navbar/navbar.html'      };  });  export default navbar;

navbar.Spec.js

import angular from 'angular';  import mocks from 'angular-mocks';  import navbar from './navbar';      describe('navbar', function () {      let scope;      beforeEach(angular.mock.module('navbar'));      beforeEach(angular.mock.inject(function ($rootScope, $controller) {          scope = $rootScope.$new();          $controller('navbarCtrl', {$scope: scope});      }));      it('Controller测试', function () {          expect(scope).to.have.property('links').with.length(2);      });  });

以上是一个简单的angular写的空间NAVBAR的测试。

至于断言库 CHAI 可以查看官方文档来了解具体的可以断言的内容。

E2E测试

E2E也就是End To End,就是所谓的“用户真实场景”。这个测试比较系统,基于E2E测试的开发也是敏捷开发的一种。angularJS官方实例中已经给了一个E2E的测试例子。使用的工具是protractor。也是angularJS给的测试工具。大致看了 API 感觉到功能还是很强的。不过说实话没有具体细看每个API,这个文档先留着以后具体问题在看吧。

protractor-conf.js

exports.config = {      allScriptsTimeout: 10000,        specs: [          '*.js'      ],        capabilities: {          'browserName': 'chrome'      },        chromeOnly: true,      baseUrl: 'http://localhost:3000/',      framework: 'mocha',      mochaOpts: {          timeout: 10000      }  };

记得设置下TIMEOUT时间,以防测试任务功能时间太长timeout了

HomeE2E.js

var chai = require('chai');  var chaiAsPromised = require('chai-as-promised');  chai.use(chaiAsPromised);  var expect = chai.expect;    describe('HomeE2E', function() {      beforeEach(function() {          browser.get('/');      });        it('测试LINKS', function() {          var todoList = element.all(by.repeater('x in links'));          expect(todoList.get(1).getText()).to.eventually.equal('about');          expect(todoList.get(0).getText()).to.eventually.equal('home');      });        it('测试输入框', function() {          var HomeInput = element(by.model('HomeInput'));          var Hometext = element(by.id('Hometext'));          HomeInput.sendKeys('nexus');          expect(Hometext.getText()).to.eventually.equal('nexus');          HomeInput.clear();      });  });

以上是一个简单的测试代码。

测试覆盖率

karma-coverage这个是一个KARMA判断测试代码覆盖率的一个工具,但是由于我们用的ES6编写的源代码,所以这个覆盖率测试结果是编译后的代码,测试的覆盖率没有实际意义。所以这个工具没有出现在我的项目中。不过代码覆盖率测试还是很重要的。在不使用ES6的情况下还是可以使用karma-coverage来统计下单元测试的代码覆盖率的。(我还在找ES6的代码覆盖率的解决方法,毕竟ES6是未来的一个方向。所以提前问道也是有好处的。)

有兴趣的可以去 zchq88_seed 这个项目看看。

来自: http://segmentfault.com/a/1190000004265119