Page 280 - AngularJS权威教程
P. 280
260 第 19 章 测试
angular.module('myApp.services', [])
.value('version', '0.0.1');
在这个情况下,服务提供了一个字符串值。我们可以把这个版本服务注入到当前测试中。
单元测试的样板看上去像这样:
describe('Unit: services', function() {
beforeEach(module('myApp'));
});
到现在为止,我们已经隐式调用过$injector服务了。本例展示了如何显式调
用它。
为隔离这个测试,我们把它嵌套在一个describe()块中,并且在beforeEach()块中注入了
版本服务。
describe('version', function() {
var version;
beforeEach(inject(function($injector) {
// 使用$injector获取版本服务
version = $injector.get('version');
}));
it('should have the version as a service',
function() {
// 设置对版本服务的预期
expect(version).toEqual('0.0.1');
});
});
正如我们所看到的,测试服务真是简单,然而,我们的服务并不总是这么简单。在示例应用
中,我们跟googleApi交互,这个服务就有些复杂了。
这是googleService.googleApi服务的完整源码:
// google服务模块
angular.module('googleServices', [])
.factory('googleApi',
function($window, $document, $q, $rootScope) {
// 创建了一个defer
// 封装了我们的Google API服务的加载
var d = $q.defer();
// 脚本被浏览器加载之后,
// 我们就要调用这个函数了,
// 它反过来会解析我们的全局defer
$window.bootGoogleApi = function(keys) {
// 需要设置我们的API key
window.gapi.client.setApiKey(keys.apiKey);
$rootScope.$apply(function() {
d.resolve(keys);
});
};
// 在浏览器中加载客户端
var scriptTag = $document[0].createElement('script');
scriptTag.type = 'text/javascript';