Page 279 - AngularJS权威教程
P. 279
19.14 测试一个应用 259
describe('E2E controllers: ', function() { 19
// 我们的测试代码放在这里
});
测试建立好了之后,就可以添加细则了。我们要测试日期(或者至少它的一部分)存在于页 20
面上,时区也在。
beforeEach(function() { 21
browser().navigateTo('/#/');
});
22
it('should have the date in the browser', function() {
var d = new Date();
expect(
element("#time h1").html() 23
).toMatch(d.getFullYear());
});
24
it('should have the user timezone in the header', function() {
expect(
element('header').html()
).toMatch('US/Pacific'); 25
});
想知道timeout函数在控制器上被调用了,也比较方便。可以使用Jasmine帮助函数createSpy 26
来确认timeout确实被调用了。
如果修改了beforeEach()函数(看上面),可以在控制器中包含$timeout服务。 27
var FrameController, scope, timeout;
beforeEach(inject(
function($controller, $rootScope) { 28
scope = $rootScope.$new();
timeout = jasmine.createSpy('timeout');
FrameController = $controller('FrameController', { 29
$scope: scope,
$timeout: timeout
});
})); 30
现在,在测试中可以设置一个预期:服务确实被调用了:
31
it('should set the clock a foot', function() {
expect(timeout).toHaveBeenCalled();
});
32
19.14.4 测试服务和工厂
33
服务是很容易测试的:它们是独立的对象,提供了本地化的功能。既然它们是单例对象,我
们可以隔离地创建这些对象,测试它们的行为。
34
1. 单元测试服务
单元测试服务非常容易,我们只要把服务注入到测试中就可以了。 35
用一个简单例子开始吧,设想我们有一个服务提供了版本信息:
36