DIV CSS 佈局教程網

在 AngularJS 中撰寫單元測試的實務指南
編輯:JavaScript綜合知識     

單元測試的價值幾乎是開發者的共識:它替你守住程式碼品質,讓重構時更有底氣。AngularJS 自詡高可測試性,官方文件也提供了端到端測試的實例;但真正動手時,仍有不少眉角。本文記錄一套可運用的做法。

Karma:測試執行器

Karma 是 Angular 團隊打造的 JavaScript 測試執行器,能自動跑完測試任務,取代繁瑣的手工操作(例如回歸測試、載入相依)。它與 Angular 的搭配堪稱天作之合。

定義好設定檔並啟動後,Karma 就會在指定的瀏覽器環境中自動執行測試。以下是一份實際專案使用的設定:

module.exports = function (config) {
    config.set({
        basePath: '../',

        files: [
            'app/lib/angular/angular.js',
            'app/lib/angular/angular-*.js',
            'app/js/**/*.js',
            'test/lib/recaptcha/recaptcha_ajax.js',
            'test/lib/angular/angular-mocks.js',
            'test/unit/**/*.js'
        ],

        exclude: [
            'app/lib/angular/angular-loader.js',
            'app/lib/angular/*.min.js',
            'app/lib/angular/angular-scenario.js'
        ],

        autoWatch: true,
        frameworks: ['jasmine'],
        browsers: ['PhantomJS'],

        plugins: [
            'karma-junit-reporter',
            'karma-chrome-launcher',
            'karma-firefox-launcher',
            'karma-jasmine',
            'karma-phantomjs-launcher'
        ],

        junitReporter: {
            outputFile: 'test_out/unit.xml',
            suite: 'unit'
        }
    });
};

它與 angular-seed 的預設設定相近,差異在於:瀏覽器從 Chrome 換成 PhantomJS,如此跳轉時不必另開視窗;此外因專案需要 Google Recaptcha,多補了一個相依檔案。而 autoWatch: true 是相當實用的一項,它會在檔案變動時自動重跑測試。安裝方式:

npm install karma

用 Jasmine 寫測試

Jasmine 是行為驅動開發風格的測試框架,Angular 官方也推薦它。

測試一個簡單的 controller

假設有一個負責判斷頁籤是否啟用的 controller:

app.controller('NavCtrl', function ($scope, $location) {
    $scope.isActive = function (route) {
        return route === $location.path();
    };
});

要測試 isActive,思路是:注入 $location 的測試版本,設定路徑後驗證回傳值。這正是 Angular 依賴注入的用武之地。

describe('NavCtrl', function () {
    var $scope, $location, $rootScope, createController;

    beforeEach(inject(function ($injector) {
        $location = $injector.get('$location');
        $rootScope = $injector.get('$rootScope');
        $scope = $rootScope.$new();

        var $controller = $injector.get('$controller');

        createController = function () {
            return $controller('NavCtrl', { '$scope': $scope });
        };
    }));

    it('should have a method to check if the path is active', function () {
        var controller = createController();
        $location.path('/about');

        expect($location.path()).toBe('/about');
        expect($scope.isActive('/about')).toBe(true);
        expect($scope.isActive('/contact')).toBe(false);
    });
});

掌握這個基本結構後,就能變化出各類測試:在測試案例中自行加上屬性、呼叫方法、再斷言屬性是否被正確清除。

處理 $http:用 $httpBackend

如果 controller 會發出請求,Angular 提供了 $httpBackend 的 mock 版本,讓你能自訂伺服器回應,或驗證請求內容是否符合預期。

describe('MainCtrl', function () {
    var $scope, $rootScope, $httpBackend, $timeout, createController;

    beforeEach(inject(function ($injector) {
        $timeout = $injector.get('$timeout');
        $httpBackend = $injector.get('$httpBackend');
        $rootScope = $injector.get('$rootScope');
        $scope = $rootScope.$new();

        var $controller = $injector.get('$controller');

        createController = function () {
            return $controller('MainCtrl', { '$scope': $scope });
        };
    }));

    afterEach(function () {
        $httpBackend.verifyNoOutstandingExpectation();
        $httpBackend.verifyNoOutstandingRequest();
    });

    it('should run the Test to get the link data from the backend', function () {
        var controller = createController();
        $scope.urlToScrape = 'success.com';

        $httpBackend.expect('GET', '/slurp?urlToScrape=http:%2F%2Fsuccess.com')
            .respond({
                "success": true,
                "links": [
                    "https://www.google.com",
                    "https://angularjs.org",
                    "https://amazon.com"
                ]
            });

        // 必須用 $apply 觸發 $digest,HTTP 請求才會送出
        $scope.$apply(function () {
            $scope.runTest();
        });

        expect($scope.parseOriginalUrlStatus).toEqual('calling');

        $httpBackend.flush();

        expect($scope.retrievedUrls).toEqual([
            "https://www.google.com",
            "https://angularjs.org",
            "https://amazon.com"
        ]);
        expect($scope.parseOriginalUrlStatus).toEqual('waiting');
        expect($scope.doneScrapingOriginalUrl).toEqual(true);
    });
});

beforeEach 的結構與前面類似,只是改成向 injector 取得 $httpBackend。而 afterEach 這兩個驗證呼叫很重要,能確保每個案例跑完後沒有殘留的請求或期望。

有幾點不太直觀但必須記住:呼叫 $httpBackend 的方法要包在 $scope.$apply() 裡,這樣才會觸發 $digest 並真正送出請求;而直到呼叫 $httpBackend.flush() 之前,回應都不會被解析——這恰好給了我們在「請求已發出、回應尚未到來」的中途狀態做斷言的機會,例如上例中檢查 parseOriginalUrlStatus 為 'calling',flush 之後再確認它變成 'waiting'。

小結論

寫 Angular 的單元測試,最難的往往不是語法,而是「從哪裡開始」。網路上資源雖多,卻缺乏一致的實務準則。把本文的兩個範本留下來當模板——一個測純邏輯 controller、一個測帶 $http 的 controller——大部分情況都能套用,剩下的時間就能專心寫程式碼,而不是去摸索框架的種種特性。

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