我正在加速AngularJS单元测试。我最新的“珠穆朗玛峰”是对使用Foo服务工厂的Bar服务的测试:
// Foo service returns new objects having get function returning a promise
angular.module('foo', []).
factory('Foo', ['$http', function ($http) {
function FooFactory(config) {
var Foo = function (config) {
angular.extend(this, config);
};
Foo.prototype = {
get: function (url, params, successFn, errorFn) {
successFn = successFn || function (response) {};
errorFn = errorFn || function (response) {};
return $http.get(url, {}).then(successFn, errorFn);
}
};
return new Foo(config);
};
return FooFactory;
}]);
// Bar services uses Foo service
angular.module('bar', ['foo']).
factory('Bar', ['Foo', function (Foo) {
var foo = Foo();
return {
getCurrentTime: function () {
return foo.get('foo.json', {}, function (response) {
return Date.parse(response.data.now);
});
}
};
}]);
单元测试存根Foo服务工厂。
'use strict';
describe('bar tests', function () {
var currentTime, currentTimeInMs, $q, $rootScope, mockFoo, mockFooFactory, Foo, Bar, now;
currentTime = "March 26, 2014 13:14 UTC";
currentTimeInMs = Date.parse(currentTime);
beforeEach(function () {
// stub out enough of Foo to satisfy Bar service:
// create mock object with function get: function(url, params, successFn, errorFn)
// that promises to return a response with this property
// { data: { now: "March 26, 2014 13:14 UTC" }})
mockFoo = {
get: function (url, params, successFn, errorFn) {
successFn = successFn || function (response) {};
errorFn = errorFn || function (response) {};
// need to setup deferred promise
var deferred = $q.defer();
deferred.resolve({data: { now: currentTime }});
return (deferred.promise).then(successFn, errorFn);
}
};
// create mock Foo service
mockFooFactory = function(config) {
return mockFoo;
};
module('foo', function ($provide) {
$provide.value('Foo', mockFooFactory);
});
module('bar');
inject(function (_$q_, _$rootScope_, _Foo_, _Bar_) {
$q = _$q_;
$rootScope = _$rootScope_;
Foo = _Foo_;
Bar = _Bar_;
});
});
it('getCurrentTime should return currentTimeInMs', function () {
Bar.getCurrentTime().then(function (serverCurrentTime) {
now = serverCurrentTime;
});
$rootScope.$apply(); // resolve Bar promise
expect(now).toEqual(currentTimeInMs);
});
});
我可以使用Jasmine的间谍功能来模拟Foo服务工厂吗?如果是这样,怎么样?