【发布时间】:2015-08-29 15:19:07
【问题描述】:
我有以下控制器
app.controller('NavController', ['$rootScope', '$scope', 'api', function($rootScope, $scope, $location, auth, api) {
$scope.load = function() {
return api.get('/location').success(function(data) {
$rootScope.locations = data;
}).error(function(data) {
console.log('load error');
});
};
}]);
这是我为它编写的单元测试
describe('Navigation Controller Test', function() {
beforeEach(module('app'));
var controller, scope, rootScope, httpBackend;
beforeEach(inject(function(_$controller_, _$rootScope_, $httpBackend) {
var $controller = _$controller_;
rootScope = _$rootScope_;
scope = rootScope.$new();
httpBackend = $httpBackend;
controller = $controller('NavController', {
$rootScope: rootScope,
$scope: scope,
});
apiRequestHandler = httpBackend.when('GET', '/api/v2/location')
.respond({userId: 'userX'});
}));
afterEach(function() {
httpBackend.verifyNoOutstandingExpectation();
httpBackend.verifyNoOutstandingRequest();
});
describe('load()', function() {
it('should have locations when successful', function() {
httpBackend.expectGET('/api/v2/location');
scope.load();
expect(rootScope.locations).toEqual("{userId: 'userX'}");
httpBackend.flush();
});
});
});
我遇到的当前问题是,即使在调用 scope.load() 函数之后,rootScope.locations 也未定义。我不太确定这是为什么,但我似乎找到的最接近的帖子是 this 一个我认为可能与我的问题有关但我不太确定的帖子。
当获取请求成功并且它具有正确的输出时,我在控制器中执行了console.log($rootScope.locations),但是我不知道如何让它在此测试中显示相同。
【问题讨论】:
标签: angularjs unit-testing angularjs-scope jasmine