如何在Karma单元测试中解析控制器中的$ q.all?

时间:2015-05-06 16:03:18

标签: angularjs q karma-jasmine

我的控制器有:

GetValue()

我的测试是

        switchUserAccount: function() {
            $scope.model.currentMode = 'user';
            console.log(ipCookie('currentPatientId'));
            $q.all([facilityCache.getFacility(), facilityGroupCache.getGroupList(), languageCache.getLanguageList(), genderCache.getGenderList(), raceCache.getRaceList(), dosingCache.getDosingOptions()])
                .then(function(){
                    console.log('back from then');
                    cache.set('ui', 'adminPage', '');
                    cache.set('ui', 'schedulePage', 'patients');
                    if(ipCookie('currentPatientId')) {
                        $location.path('/patient/view/' + ipCookie('currentPatientId'));
                    } else {
                        $location.path('/patients');
                    }
                });
        },

所以我期望发生的是describe('MainHeaderController', function() { var scope, $rootScope, $locationMock, $httpBackend; beforeEach(function() { module('mapApp'); return inject(function($injector) { var $controller, $q, ipCookieMock; $rootScope = $injector.get('$rootScope'); $controller = $injector.get('$controller'); $httpBackend = $injector.get('$httpBackend'); $q = $injector.get('$q'); $locationMock = jasmine.createSpyObj('$location', ['path']) ipCookieMock = function() { return 123; } scope = $rootScope.$new() $controller('MainHeaderController', { $scope: scope, $location: $locationMock, $q: $q, ipCookie: ipCookieMock }); $httpBackend.whenGET('/rpc/session').respond(200); $httpBackend.whenPOST('/rpc').respond(200); return scope.$digest(); }); }); it('should redirect to a patient view if a cookie is set', function($rootScope) { scope.switchUserAccount(); // $rootScope.$apply(); expect($locationMock.path).toHaveBeenCalledWith('/patient/view/123'); }); }); $location.path一起调用。相反,我得到的是

/patient/view/123

如果我取消注释Expected spy $location.path to have been called with [ '/patient/view/123' ] but actual calls were [ ]. ,我会

$rootScope.$apply()

那么如何在我的控制器中触发TypeError: 'undefined' is not a function (evaluating '$rootScope.$apply()') 以便测试可以正常通过?

谢谢!

1 个答案:

答案 0 :(得分:1)

您通过将其声明为测试函数的参数来隐藏测试套件的$rootScope变量。这就是为什么它是未定义的:jasmine调用测试函数输出任何参数。

替换

it('should redirect to a patient view if a cookie is set', function($rootScope) {

通过

it('should redirect to a patient view if a cookie is set', function() {
相关问题