目錄結(jié)構(gòu):
首先我們來看一下一個project創(chuàng)建好之后,整個工程的目錄結(jié)構(gòu):
其中工具會自動生成test目錄侠畔,其中放置對controllers的單元測試代碼,main.js和about.js都是自動生成的损晤。一般情況下软棺,app/scripts/controllers下的每個文件都對應(yīng)一個測試代碼。
代碼邏輯:
業(yè)務(wù)代碼:
/**
* Created by jrzhaoxueyong on 2017/3/8.
*/
'use strict';
angular.module('webApp')
.controller('LoginCtrl', function ($rootScope, $location, $scope, AuthService) {
$scope.loginUser = function (credentials) {
$scope.credentials = {
username : '',
password : ''
};
console.log('login:', credentials);
AuthService.login(credentials);
$location.path('/natgw')
};
$rootScope.isUserAuthenticated = function () {
return AuthService.isAuthenticated();
}
});
測試代碼:
'use strict';
describe('Controller: LoginCtrl', function () {
// load the controller's module
beforeEach(module('webApp'));
it('should have a method to check user is authenticated', function () {
// Initialize the controller and a mock scope
inject(function ($controller, $rootScope, $location) {
var scope = $rootScope.$new();
var authService = {
isAuthenticated: function () {
return true;
}
};
$controller('LoginCtrl', {
$scope: scope,
// place here mocked dependencies
AuthService: authService,
$rootScope: $rootScope,
$location: $location
});
expect($rootScope.isUserAuthenticated()).toBe(true);
});
});
});
上述是最簡單的測試套尤勋,針對Controller
做相關(guān)測試其他如Directives
喘落、Filters
茵宪、Factories
可以參考文章結(jié)尾的參考資料。代碼樣例是驗證isUserAuthenticated
方法的瘦棋。下面對這段代碼做一個解剖:
-
describe屬性:
describe
參數(shù)是一個全局的Jasmine方法稀火,定義了一個測試套。其中有兩個參數(shù):一個字符串表示這個測試套的標題兽狭;一個函數(shù)是實現(xiàn)這個測試套的具體代碼塊憾股。describe("A Test Suite", function() { })
-
beforeEach屬性:
主要用來設(shè)置測試套的前置規(guī)則鹿蜀,相當于
setup
箕慧,與afterEach
作用相似,afterEach
作用于teardown
相似茴恰。beforeEach(module('webApp')); //module即加載了webApp模塊
-
it屬性:
一般一個
it
對應(yīng)一個用例可以包含一個或多個expect
方法倍奢,it
有兩個入?yún)⒌苁矗谝粋€字符串表示這個用例的標題,第二個函數(shù)是這個用例的具體實現(xiàn)。it('should have a method to check user is authenticated', function () { });
-
inject屬性:
打樁一些參數(shù)和方法印蔬,比如業(yè)務(wù)代碼中需要
$scope
、$rootScope
派哲、$location
偎血、AuthService
四個入?yún)ⅲ渲行枰獙?code>AuthService進行打樁雕沉,因為這是自定義Service
集乔,此外$scope
是局部參數(shù),這里需要從$rootScope
生成坡椒。其他兩個參數(shù)都是全局參數(shù)扰路,且不涉及自定義的屬性。var scope = $rootScope.$new(); var authService = { isAuthenticated: function () { return true; } };
-
$controller屬性:
這個屬性很重要倔叼,它用來實例化
controller
汗唱,并把自己定義好的樁函數(shù)傳遞進去。這樣后續(xù)expect
就能得到想要的結(jié)果了丈攒。$controller('LoginCtrl', { $scope: scope, // place here mocked dependencies AuthService: authService, $rootScope: $rootScope, $location: $location });
-
expect屬性:
主要的測試函數(shù)哩罪,執(zhí)行一個表達式,并對結(jié)果做驗證巡验。其中际插,驗證的方法包括這里用到的
toBe
、toEqual
深碱、toContain
腹鹉、toMatch
、toBeDefined
等敷硅。expect($rootScope.isUserAuthenticated()).toBe(true);
執(zhí)行用例:
至此功咒,整個測試用例就寫完了愉阎,下面看看運行結(jié)果:
Controller\web> grunt test