AngularJS測試二 jasmine測試路由 控制器 過濾器 事件 服務

來源:互聯網
上載者:User

標籤:

測試應用

1.測試路由我們需要檢測路由是否在運作,是否找到了,或者是404了。我們要確認路由事件觸發了,預期的模板是否真的載入了。既然路由會改變頁面的地址(URL)和頁面內容,我們需要檢測路由是否被載入了,頁面是否找到了,在這中間發生了什麼。一段簡單的路由代碼:angular.module(‘myApp‘, [‘ngRoute‘])
.config(function($routeProvider) {
$routeProvider
.when(‘/‘, {
templateUrl: ‘views/main.html‘,
controller: ‘HomeController‘})
.when(‘/login‘, {
templateUrl: ‘views/login.html‘,
controller: ‘LoginController‘})
.otherwise({redirectTo ‘/‘});
})測試路由我們需要做以下幾件事:(1)注入$route、$location和$rootScope服務。
(2)建立一個類比的後端來處理XHR,擷取模板代碼。
(3)設定一個地址,運行一個$digest生命週期Step1:在測試中引用服務,並設定一個類比後端,從templateUrl擷取模板。可以用$httpBackend來建立斷言來判斷指定模板被載入了.describe(‘Routes test‘, function() {
// 在測試中類比模組
beforeEach(module(‘myApp‘));
var location, route, rootScope;
beforeEach(inject(
function(_$location_, _$route_, _$rootScope_) {
location = _$location_;
route = _$route_;
rootScope = _$rootScope_;
}));
describe(‘index route‘, function() {
beforeEach(inject(
function($httpBackend) {
$httpBackend.expectGET(‘views/home.html‘)
.respond(200, ‘main HTML‘);
}));
// 我們的測試代碼放在這裡
});
});Step2:為了用單元測試來測試路由,我們需要類比路由在生產中的運作。路由藉助於digest生命週期來運行,當location被設定以後,它使用一個digest重複持續時間來處理路由,改變頁面內容,然後結束本次路由。瞭解了這些之後,我們就需要解釋測試中路徑的變更。在測試中,我們打算在應用的index路由上測試兩個狀態:當使用者導航到首頁時,指定的控制器會給他們顯示首頁;當使用者導航到一個未知路由時,他們會按照在otherwise函數中定義的那樣被帶到首頁。我們可以通過建立$location服務來傳遞路徑的方式測試這些條件。為了觸發location請求,我們要運行一個digest周期(在$rootScope上),然後檢測控制器是符合預期的(在本例中,是“HomeController”)。it(‘should load the index page on successful load of /‘,
function() {
location.path(‘/‘);
rootScope.$digest(); // 調用digest迴圈
expect(route.current.controller)
.toBe(‘HomeController‘)
});
it(‘should redirect to the index path on non-existent
route‘, function() {
location.path(‘/definitely/not/a/_route‘);
rootScope.$digest();
expect(route.current.controller)
.toBe(‘HomeController‘)});2.測試控制器在建立單元測試的過程中,需要確保:
建立了測試來類比模組;
用一個已知的範圍執行個體來儲存控制器的一個執行個體;
基於範圍來測試我們的預期。要初始化一個控制器執行個體,需要使用$new()方法從$rootScope建立某範圍的一個新執行個體。這個新執行個體會建立Angular在運行時使用的範圍繼承。有了這個範圍,就可以初始化一個新的控制器,把這個範圍作為控制器的$scope傳遞過去。describe(‘Unit controllers: ‘, function(){
// 類比myApp模組
beforeEach(module(‘myApp‘));
describe(‘FrameController‘, function() {
// 局部變數
var FrameController, scope;
beforeEach(inject(
function($controller, $rootScope) {
// 建立子範圍
scope = $rootScope.$new();
// 建立FrameController的新執行個體
FrameController = $controller(‘FrameController‘,
{ $scope: scope });
}));
// 我們的測試代碼放在這裡
});});在FrameController裡,我們有一個時鐘在應用頂部顯示目前時間。我們也可以訪問一個使用者和他的時區。具體的控制器的代碼如下angular.module(‘myApp.controllers‘, [])
.controller(‘FrameController‘,
function($scope, $timeout) {
$scope.time = {
today: new Date()
};
$scope.user = {
timezone: ‘US/Pacific‘
}
var updateClock = function() {
$scope.time.today = new Date();
};
var tick = function() {
$timeout(function() {
$scope.$apply(updateClock);
tick();
}, 1000);
}
tick();});我們要測試控制器的兩個功能:時間已被定義;使用者已被定義,並且有時區。it(‘should have today set‘, function() {
expect(scope.time.today).toBeDefined();
});
it(‘should have a user set‘, function() {
expect(scope.user).toBeDefined();});再舉個簡單易懂的例子://建立一個scope對象,true表示它不會繼承父級的變數,以免帶來困擾var scope=$rootScope.$new(true);//找到SomeController,並對scope進行初始化$controller(‘$SomeController‘,{$scope:scope});  //在這裡也可以注入其他被mock的service或resolve的對象//期待scope上應該出現一個name屬性,其值為some one$expect(scope.name).toEqual(‘some one‘);//期待scope上應該出現一個greeting函數,調用它後的值為hello,some one$expect(scope.greeting()).toEqual(‘hello,some one‘);3.測試工廠和服務Service可以是函數,可以是類,也可以是變數,所以測試起來沒什麼固定的形式,但是步驟和原理是相似的。注入這個Service,把它儲存為一個變數;如果是函數,就調用它;如果是類,就new它,然後檢查成員;如果是變數,就對比它的值。var myClass;//注入beforeEach(inject(function(_MyClass_){     MyClass=_MyClass_;   //賦給外部變數,以便後面的測試中使用}));it(‘someMethod should be 2‘,function(){     var obj=new MyClass();     expect(obj.someMethod()).toEqual(2);});4.測試過濾器首先,要訪問過濾器,只需簡單地把$filter服務注入到我們的測試中。這樣我們就得到了一個在此過程中尋找過濾器的途徑:
describe(‘Unit: Filter tests‘, function() {
var filter;
// 在測試中類比我們的引用
beforeEach(module(‘myApp‘));
beforeEach(inject(function($filter) {
filter = $filter;
}));
});
有了對控制器的訪問,在過濾器的輸出上設定預期就是很容易的事了。
it(‘should give us two decimal points‘,
function() {
expect(filter(‘number‘)(123, 2)).toEqual(‘123.00‘);
});5.測試模板測試模板時,我們著重於確保:特定的內容範本被載入了,模板中特定的資料也在視圖中顯示了。可以建立一個斷言:模板正常載入了。要做到這個,需要建立測試來期望對首頁模板的一個請求,並且執行一個視圖的變更來驗證它是不是真的載入了。describe(‘Unit: Templates‘, function() {
var $httpBackend,
location,
route,
rootScope;
beforeEach(module(‘myApp‘));
beforeEach(inject(
function(_$rootScope_, _$route_, _$httpBackend_, _$location_){
location = _$location_;
rootScope = _$rootScope_;
route = _$route_;
$httpBackend = _$httpBackend_;
}));
afterEach(function() {
$httpBackend.verifyNoOutstandingExpectation();
$httpBackend.verifyNoOutstandingRequest();
});
// 我們的測試代碼放在這裡
});
現在,可以建立測試來反映導航到應用不同部分時的預期。
it(‘loads the home template at /‘, function() {
$httpBackend.expectGET(‘templates/home.html‘)
.respond(200);
location.path(‘/‘);
rootScope.$digest(); // 調用digest迴圈
$httpBackend.flush();
});
it(‘loads the dashboard template at /dashboard‘, function() {
$httpBackend.expectGET(‘templates/dashboard.html‘)
.respond(200);
location.path(‘/dashboard‘);
rootScope.$digest(); // 調用digest迴圈
$httpBackend.flush();
});注意,我們並未在測試中返回一個模板(是.respond(200),而不是.respond(200, "\<div\>\</div\>"))。鑒於我們只是在驗證模板是否在請求中載入了,沒有必要擔心到底顯示了什麼。6.測試事件當對事件的觸發進行單元測試時,我們感興趣的是它們究竟調用了什麼,還有是否真的調用了正確的事件。其次,我們主要關心處理常式有它們需要的資料。
使用Jasmine的輔助方法spnOn()可以非常容易地建立事件測試。設想我們在測試一個控制器,它觸發了一個$emit函數。基於這個函數,我們可以建立一個預期:事件被觸發了,並且用我們所感興趣的任意參數調用了。describe(‘myApp‘, function() {
var scope;
beforeEach(angular.mock.module(‘myApp‘));
beforeEach(angular.mock.inject(function($rootScope) {
scope = $rootScope.$new();
});
});
測試建好之後,就可以簡單地在範圍上為$emit或者$broadcase事件設定一個spyOn()調用了。

// ...
});
it(‘should have emit called‘, function() {
spyOn(scope, "$emit");
scope.closePanel(); // 樣本
// 或者任意可能導致emit被調用的事件
expect(scope.$emit)
.toHaveBeenCalledWith("panel:closed",
panel.id);
});
我們也可以測試事件:設定一個事件觸發後調用的$on()監聽器。要執行$broadcast方法,
可以簡單地在範圍上調用$broadcast,並且對事件將會導致的範圍變化建立一個預期。
// ...
it(‘should set the panel to closed state‘,
function() {
scope.$broadcast("panel:closed", 1);
expect(scope.panel.state).toEqual("closed");
});

AngularJS測試二 jasmine測試路由 控制器 過濾器 事件 服務

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.