與karma、angular的第一次親密接觸

  首先要了解什麼是karma,karma幹嗎用的,它的好朋友jasmine又是啥?這些文章能夠幫助你:
  karma幹嗎的?
  angular與karma1
  angular與karma2
  看了以上幾篇文章以後,咱們基本上就能夠啓動咱們最簡單的一個karma測試例子了。而後咱們還要有webpack對吧:
  karma-webpack插件
  這些都配置好,咱們的karma配置文件就成了這個樣子:javascript

// Karma configuration
// Generated on Sun Dec 04 2016 19:19:27 GMT+0800 (中國標準時間)

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: [ 'test/**/*.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: { 'test/**/*.js': ['webpack','coverage'] }, // test results reporter to use // possible values: 'dots', 'progress' // available reporters: https://npmjs.org/browse/keyword/karma-reporter reporters: ['progress','coverage'], // 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: { module: { debug: true, module: { loaders: [ // nothing here yet! We'll add more stuff in Part 2 ] } } }, webpackServer: { noInfo: true // prevent console spamming when running in Karma! }, plugins: [ 'karma-chrome-launcher', 'karma-webpack', 'karma-jasmine', 'karma-coverage' ], coverageReporter: { type : 'html', dir : 'coverage/' } }) } 

  app.js中的內容php

var angular = require('angular');

var mamApp = angular.module("mamApp",[
    require('angular-ui-router'),
    require('./modules/listsModule.js'),
    require('./modules/detailModule.js')
    ]);
mamApp.controller('mamAppModuleCtrl', function($scope,$http,$state,$stateParams) {
    var listType = $stateParams.listType;
    var state = $state.current.name;
    $scope.listType = listType;
    $scope.menuData = [
        {
            id:"appManage",
            name:"應用管理"
        }
    ];
});

  test文件夾裏寫了一個testIndex.js。css

var angular = require('angular');
var mocks = require('angular-mocks');
var mamApp = require('../src/js/app.js');
describe("mamApp", function() {
    var scope;
    beforeEach(angular.mock.module('mamApp'));
    beforeEach(angular.mock.inject(function ($rootScope, $controller) {
        scope = $rootScope.$new();
        $controller('mamAppModuleCtrl', {$scope: scope});
    }));
    it("menuData", function() {
        expect(scope.menuData[0].id==="appManage").toBe(true);
    });
    it("listType", function() {
        scope.listType="white";
        expect(scope.listType=="white").toBe(true);
    });
});

  而後開跑,cmd裏輸入:karma start
  ok,沒問題,順利運行。控制檯打出兩個綠色的success。
  那我如今要測試listsModule這個子模塊了,它是app的依賴模塊,想固然的代碼寫成這樣:
  新建一個文件:testListModule.jshtml

var angular = require('angular');
var mocks = require('angular-mocks');
var mamApp = require('../src/js/app.js');
describe("listsModuleWhite", function() {
    var scope;
    beforeEach(angular.mock.module('listsModule'));
    beforeEach(angular.mock.inject(function ($rootScope,$http,$state,$stateParams,$controller) {
        scope = $rootScope.$new();
        $stateParams.listType="white";
        $controller('listsModuleCtrl', {$scope: scope,$http:$http,$state:$state,$stateParams:$stateParams});
    }));
    it("when listType is white scope.listType should be white", function() {
        expect(scope.listType==="white").toBe(true);
    });
    it("when listType is white btnsShow should be false", function() {
        expect(scope.btnsShow).toBe(false);
    });
    it("when listType is white scope.colNames[1].html should be 版本號", function() {
        expect(scope.colNames[1].html==="版本號").toBe(true);
    });
});

  運行起來報錯。。。一個是報屢次引用angular的錯誤,另外老是報找不到的stateprovider,通過錯誤分析應該改爲這樣:java

describe("listsModuleWhite", function() {
    var scope;
    beforeEach(angular.mock.module('mamApp'));//注意這行
    beforeEach(angular.mock.module('listsModule'));
    beforeEach(angular.mock.inject(function ($rootScope,$http,$state,$stateParams,$controller) {
        scope = $rootScope.$new();
        $stateParams.listType="white";
        $controller('listsModuleCtrl', {$scope: scope,$http:$http,$state:$state,$stateParams:$stateParams});
    }));
    it("when listType is white scope.listType should be white", function() {
        expect(scope.listType==="white").toBe(true);
    });
    it("when listType is white btnsShow should be false", function() {
        expect(scope.btnsShow).toBe(false);
    });
    it("when listType is white scope.colNames[1].html should be 版本號", function() {
        expect(scope.colNames[1].html==="版本號").toBe(true);
    });
});

  注意這行:webpack

beforeEach(angular.mock.module('mamApp'));

  把它加在子模塊的實例化以前。就解決了哪些unknown provider的錯誤。
  那麼好,咱們繼續寫一個文件測試DetailModule,固然是模仿前一個寫成這樣:angularjs

describe("detailModuleWhite", function() {
    var scope;
    beforeEach(angular.mock.module('mamApp'));
    beforeEach(angular.mock.module('detailModule'));
    beforeEach(angular.mock.inject(function ($rootScope,$http,$state,$stateParams,$controller) {
        scope = $rootScope.$new();
        $stateParams.listType="white";
        $controller('detailModuleCtrl', {$scope: scope,$http:$http,$state:$state,$stateParams:$stateParams});
    }));
    it("when listType is white scope.listType should be white", function() {
        expect(scope.listType==="white").toBe(true);
    });
    it("when listType is white params should be ...", function() {
        expect(scope.params.deviceNum).toBe(0);
        expect(scope.params.backBtnName=="返回白名單列表").toBe(true);
    });

});

  而後又報錯,說angular undefined。
  仔細分析了一下,各類方法都測了一遍,最後發現是代碼執行順序錯誤了。Detail這個文件應爲名字開頭是D,先於Index(開頭是I)文件運行了。因此我就把「Index」文件改了個名字叫「1ndex」,這樣代碼又順利運行了。
  而後仔細回想了一下,配置文件裏,files配置的是一個array,並且是有順序的。因此我把index文件名改回來,把karma.config.js的內容稍微改一行:web

files: [
      'test/index.js','test/modules/**/*.js'
    ],

除了index.js,其餘要測試的文件都放到modules文件夾內。
  同時爲了讓coverage分析準確,把index.js的內容改成:sql

var angular = require('angular');
var mocks = require('angular-mocks');
var mamApp = require('../src/js/app.js');
實際的測試內容代碼,放到一個新建的testMamApp.js文件內,再把這個文件放入modules文件夾內。弄完之後的結構以下:
test:.
│  Index.js
│
└─modules
        testDetailModule.js
        testListModule.js
        testMamApp.js
好了,這樣karma就能夠陪伴咱們一塊兒愉快的開發了。
![coverage效果](https://img-blog.csdn.net/20161214103626988?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvc2lzaWVyZGE=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast)
相關文章
相關標籤/搜索