我有一个触发HTTP请求的服务。此请求使用$ rootScope.config对象(存储了我的基本URL),但由于某些原因,当我使用$ httpBackend时,$ rootScope未正确加载。
服务:
myAppServices.factory('Auth', function($rootScope, $http, $cookieStore){
return {
logout: function(success, error) {
$http.get($rootScope.config.apiUrl + '/users/logout').then(function(response){
}, function(response) {
});
}
测试:
describe('services', function() {
var Auth;
var $httpBackend;
var $cookieStore;
var $rootScope;
beforeEach(function() {
module('myApp.services');
});
beforeEach(inject(function($injector) {
$httpBackend = $injector.get('$httpBackend');
$cookieStore = $injector.get('$cookieStore');
$rootScope = $injector.get('$rootScope');
Helper = $injector.get('Helper');
Auth = $injector.get('Auth');
}));
afterEach(function() {
$httpBackend.verifyNoOutstandingExpectation();
$httpBackend.verifyNoOutstandingRequest();
});
describe('logout', function() {
it('should make a request and invoke callback', function() {
// I try to set $rootScope here, works in my other tests, but not in this test
$rootScope = { config: { apiUrl: 'foo' } };
var invoked = false;
var success = function() {
invoked = true;
};
var error = function() {};
$httpBackend.expectPOST('/logout').respond();
Auth.logout(success, error);
$httpBackend.flush();
$rootScope = { config: { apiUrl: 'foo' } };
expect(invoked).toEqual(true);
当我在测试中将$ rootScope设置为某个值时,它通常有效,但在此测试中则不行。
为什么使用$ httpBackend时$ rootScope在我的服务中没有config属性?
答案 0 :(得分:5)
有两个同名的东西引起混淆:
$rootScope
(实际的$rootScope
是所有Scope的祖先,并通过Angular的依赖注入注入。)$rootScope
的局部变量。为了清楚起见,我将后者称为$rootScope{var}
。
以下是发生的事情:
在某些时候,$rootScope
会被注入您服务的构造函数中(稍后在发出$http
请求时使用)。
$rootScope{var}
初始化为$injector.get('$rootScope');
返回的值
此时$rootScope
和$rootScope{var}
是相同的对象。
此行:$rootScope = { config: { apiUrl: 'foo' } };
创建新对象,并将其指定为$rootScope{var}
的值。
此时$rootScope
和$rootScope{var}
不再相同的对象。
$rootScope{var}
确实有config
属性,但您的服务将使用$rootScope
,config
对config
一无所知
要将$rootScope
属性添加到实际的$rootScope.config = { apiUrl: 'foo' };
,请更改您的代码:
{{1}}