Page 273 - AngularJS权威教程
P. 273
19.14 测试一个应用 253
var location, route, rootScope; 19
beforeEach(
inject(_$location_, _$route_, _$rootScope_) {
location = _$location_;
route = _$route_; 20
rootScope = _$rootScope_;
});
// 我们的测试代码放在这里 21
});
既然已经把服务注入到控制器里了,我们来设置一个模拟后端,从templateUrl获取模板。
可以用$httpBackend来创建断言来判断指定模板被加载了: 22
describe('Routes test', function() {
// 在测试中模拟模块 23
beforeEach(module('myApp'));
var location, route, rootScope; 24
beforeEach(inject(
function(_$location_, _$route_, _$rootScope_) {
location = _$location_;
route = _$route_; 25
rootScope = _$rootScope_;
}));
describe('index route', function() { 26
beforeEach(inject(
function($httpBackend) {
$httpBackend.expectGET('views/home.html')
.respond(200, 'main HTML'); 27
}));
// 我们的测试代码放在这里
}); 28
});
测试代码都建立完了,现在可以开始写测试了!
29
为了用单元测试来测试路由,我们需要模拟路由在生产中的运作。路由借助于digest生命周
期来运行,当location被设置以后,它使用一个digest循环周期来处理路由,改变页面内容,然
后结束本次路由。了解了这些之后,我们就需要解释测试中路径的变更。 30
在测试中,我们打算在应用的index路由上测试两个状态。
31
当用户导航到首页时,指定的控制器会给他们显示首页。
当用户导航到一个未知路由时,他们会按照在otherwise函数中定义的那样被带到首页。
32
我们可以通过建立$location服务来传递路径的方式测试这些条件。为了触发location请
求,我们要运行一个digest周期(在$rootScope上),然后检测控制器是符合预期的(在本例中,
是“HomeController”)。 33
it('should load the index page on successful load of /',
function() { 34
location.path('/');
rootScope.$digest(); // 调用digest循环
expect(route.current.controller) 35
.toBe('HomeController')
});
it('should redirect to the index path on non-existent
route', function() { 36