DIV CSS 佈局教程網

AngularJS 單元測試實戰:Karma 加 Jasmine 打造 controller、directive、filter 測試
編輯:關於JavaScript     

ng 專案一長大,單元測試就該上桌了。有的團隊 test-driven 先寫測試,有的先把功能做出來再回頭補——兩種各有代價。本文聚焦工具鏈:用 karma 搭配 jasmine 為 ng 模組寫測試。

Karma 是什麼

karma 是一個測試執行器,負責在多種環境下跑你的測試,例如 Chrome、Firefox、PhantomJS;測試框架本身則可支援 jasmine、mocha、qunit。它是一個跑在 Node.js 上的 npm 模組。

安裝測試相關的套件時建議帶上 --save-dev,畢竟這些只在開發階段用:

npm install karma --save-dev
npm install karma-junit-reporter --save-dev

安裝 karma 時會自動帶入一批常用模組,可以從它 package.json 的 peerDependencies 看到:

 "peerDependencies": {
    "karma-jasmine": "~0.1.0",
    "karma-requirejs": "~0.2.0",
    "karma-coffee-preprocessor": "~0.1.0",
    "karma-html2js-preprocessor": "~0.1.0",
    "karma-chrome-launcher": "~0.1.0",
    "karma-firefox-launcher": "~0.1.0",
    "karma-phantomjs-launcher": "~0.1.0",
    "karma-script-launcher": "~0.1.0"
  }

接著需要一份設定檔,karma 裡通常是 karma.conf.js,內容就是普通的 Node.js 模組:

module.exports = function(config){
  config.set({
    // 下面files裡的基礎目錄
    basePath : '../',
    // 測試環境需要加載的JS信息
    files : [
      'app/bower_components/angular/angular.js',
      'app/bower_components/angular-route/angular-route.js',
      'app/bower_components/angular-mocks/angular-mocks.js',
      'app/js/**/*.js',
      'test/unit/**/*.js'
    ],
    // 是否自動監聽上面文件的改變自動運行測試
    autoWatch : true,
    // 應用的測試框架
    frameworks: ['jasmine'],
    // 用什麼環境測試代碼,這裡是chrome
    browsers : ['Chrome'],
    // 用到的插件,比如chrome浏覽器與jasmine插件
    plugins : [
      'karma-chrome-launcher',
      'karma-firefox-launcher',
      'karma-jasmine',
      'karma-junit-reporter'
    ],
    // 測試內容的輸出以及導出用的模塊名
    reporters: ['progress', 'junit'],
    // 設置輸出測試內容文件的信息
    junitReporter : {
      outputFile: 'test_out/unit.xml',
      suite: 'unit'
    }
  });
};

這裡有個細節:清單中的外掛大多不必另外安裝,裝 karma 時已經帶进来了,唯一需要手動補的是 karma-junit-reporter。

Jasmine 是什麼

Jasmine 官方的說法:一個行為驅動開發的 JavaScript 測試框架,不依賴任何其他 JS 框架,不需要 DOM,語法乾淨直觀。翻成白話就是:一個 API 友善、設定成本極低的測試庫。

先看一個官方範例:

describe("A spec (with setup and tear-down)", function() {
  var foo;

  beforeEach(function() {
    foo = 0;
    foo += 1;
  });

  afterEach(function() {
    foo = 0;
  });

  it("is just a function, so it can contain any code", function() {
    expect(foo).toEqual(1);
  });

  it("can have more than one expectation", function() {
    expect(foo).toEqual(1);
    expect(true).toEqual(true);
  });
});

幾個關鍵 API:

1. describe 定義一組測試,第一個參數描述測試主題,第二個參數放實際的測試程式碼。

2. it 定義單一測試案例,同樣兩個參數:描述內容與測試邏輯。

3. expect 用來取值並與預期比對,或做其他斷言。

4. beforeEach / afterEach 分別在每個 it 前後執行,上面的例子是前處理時改值、後處理時重設。

最後要記住:describe 的作用域跟一般 JS 一樣,內層函數可以存取外層變數,就像範例中 it 存取 foo。

跑起來很簡單:

karma start test/karma.conf.js

ng 的單元測試怎麼寫

因為 ng 的模組全靠 DI 載入與實例化,官方特別提供了 angular-mocks 這個輔助工具,負責模組定義、載入與注入。

兩個最常用的方法:

module(同時掛在 window 上,可直接呼叫)用來配置要注入的模組,參數可以是字串、函數或物件:

beforeEach(module('myApp.filters'));

beforeEach(module(function($provide) {
    $provide.value('version', 'TEST_VER');
}));

它通常寫在 beforeEach 裡,這樣才能確保執行測試時 inject 拿得到設定。

inject 用來把上面配置好的依賴注入進來,方便在 it 裡使用:

angular.module('myApplicationModule', [])
    .value('mode', 'app')
    .value('version', 'v1.0.1');

  describe('MyApp', function() {

    // You need to load modules that you want to test,
    // it loads only the "ng" module by default.
    beforeEach(module('myApplicationModule'));


    // inject() is used to inject arguments of all given functions
    it('should provide a version', inject(function(mode, version) {
      expect(version).toEqual('v1.0.1');
      expect(mode).toEqual('app');
    }));


    // The inject and module method can also be used inside of the it or beforeEach
    it('should override a version and test the new version is injected', function() {
      // module() takes functions or strings (module aliases)
      module(function($provide) {
        $provide.value('version', 'overridden'); // override version here
      });

      inject(function(version) {
        expect(version).toEqual('overridden');
      });
    });
  });

底層其實就是用 angular.injector 建立一個內建的注入器,之後的依賴處理跟一般 ng 模組完全一樣。

測試 controller

被測對象:

var myApp = angular.module('myApp',[]);

  myApp.controller('MyController', function($scope) {
    $scope.spices = [{"name":"pasilla", "spiciness":"mild"},
                      {"name":"jalapeno", "spiciness":"hot hot hot!"},
                      {"name":"habanero", "spiciness":"LAVA HOT!!"}];
    $scope.spice = "hello feenan!";
});

測試腳本:

describe('myController function', function() {

  describe('myController', function() {
    var $scope;

    beforeEach(module('myApp'));

    beforeEach(inject(function($rootScope, $controller) {
      $scope = $rootScope.$new();
      $controller('MyController', {$scope: $scope});
    }));

    it('should create "spices" model with 3 spices', function() {
      expect($scope.spices.length).toBe(3);
    });

    it('should set the default value of spice', function() {
      expect($scope.spice).toBe('hello feenan!');
    });
  });

});

這裡用 $rootScope 開一個子作用域,把它傳進 $controller 去建控制器,然後直接檢查子作用域上的陣列長度與字串值。

測試 directive

被測對象:

var app = angular.module('myApp', []);

app.directive('aGreatEye', function () {
    return {
      restrict: 'E',
      replace: true,
      template: '<h1>lidless, wreathed in flame, 1 times</h1>'
  };
});

測試腳本:

describe('Unit testing great quotes', function() {
  var $compile;
  var $rootScope;

  // Load the myApp module, which contains the directive
  beforeEach(module('myApp'));

  // Store references to $rootScope and $compile
  // so they are available to all tests in this describe block
  beforeEach(inject(function(_$compile_, _$rootScope_){
    // The injector unwraps the underscores (_) from around the parameter names when matching
    $compile = _$compile_;
    $rootScope = _$rootScope_;
  }));

  it('Replaces the element with the appropriate content', function() {
      // Compile a piece of HTML containing the directive
      var element = $compile("<a-great-eye></a-great-eye>")($rootScope);
      // fire all the watches, so the scope expression 1 will be evaluated
      $rootScope.$digest();
      // Check that the compiled element contains the templated content
      expect(element.html()).toContain("lidless, wreathed in flame, 2 times");
  });
});

幾個要點:注入 $compile 與 $rootScope,一個負責編譯 HTML,一個負責提供作用域;參數前後加底線時 ng 會自動剝掉,這是為了避免與全域變數衝突的常見技巧。用 $compile 包一層原始 HTML、再把 $rootScope 傳進返回的函數,就完成了作用域與視圖的綁定;接著呼叫 $digest 觸發所有 watcher,讓模板中的運算式真正被求值。最後比對元素 HTML 與預期內容。

測試 filter

被測對象:

var app = angular.module('myApp', []);
app.filter('interpolate', ['version', function(version) {
  return function(text) {
    return String(text).replace(/\%VERSION\%/mg, version);
  };
  }]);

測試腳本:

describe('filter', function() {
  beforeEach(module('myApp'));

  describe('interpolate', function() {

    beforeEach(module(function($provide) {
      $provide.value('version', 'TEST_VER');
    }));


    it('should replace VERSION', inject(function(interpolateFilter) {
      expect(interpolateFilter('before %VERSION% after')).toEqual('before TEST_VER after');
    }));
  });
});

先載入模組,再用 $provide 把 filter 依賴的 version 換成測試用的值,最後用 inject 取 filter——注意名稱要加上 Filter 後綴,也就是 interpolateFilter。呼叫它並比對輸出即可。

結語

用測試驅動 ng 開發有兩個明顯好處:模組更穩定,而且你會被迫理解 ng 的內部運作。還沒補測試的同學,值得排進待辦。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved