无法获得routeParams或spyOn来处理角度范围方法

时间:2015-03-17 17:01:58

标签: angularjs jasmine

我遇到了这个测试的两个问题。首先,我尝试将路由参数设置为1,因为在我的控制器中,如果设置了routeParam.id,它将只调用loadJob方法。当我在测试运行时在控制器中执行$ routeParams.id的console.log时,它会写出undefined。所以,我不确定为什么路由参数不能从测试进入控制器。

其次,如果我注释掉对routeParams的if检查并让它调用$ scope.loadJob,则spyOn失败。我在这里做错了什么想法?

spec -

describe('ApplyController', function() {
    var httpBackend, scope, job;

    beforeEach(module('jobBoard'))

    describe('loads the proper job', function(){
        beforeEach(inject(function($rootScope, $controller, $httpBackend, $http, $q, $upload, $log, templates){
            httpBackend = $httpBackend;
            scope = $rootScope.$new();
            job = { id: 1, positionTitle: 'test' };
            httpBackend.when('GET', templates.apiUrl + '/job/1').respond(job);
            $controller('JobController', {
                $scope: scope,
                $routeParams: {id:1},
                $http: $http,
                $q: $q,
                $upload: $upload,
                $log: $log,
                templates: templates
            });
            spyOn(scope, 'loadJob');
        }))

        it('calls loadJob when id route parameter is provided', function(){
            httpBackend.flush();
            scope.$digest();
            expect(scope.loadJob).toHaveBeenCalled();
        })
    })
})

...控制器

angular.module('jobBoard').controller('ApplyController',
    ['$scope','$routeParams', '$http', '$q', '$upload', '$log', 'templates', function($scope, $routeParams, $http, $q, $upload, $log, templates){

        $scope.job = {};
        $scope.pageTitle = '';
        $scope.jobId = 0;

        $scope.loadJob = function(){
            var deferred = $q.defer();

            $http.get(templates.apiUrl + '/job/' + $routeParams.id)
                .success(function(data){
                    $scope.job = data;
                    $scope.pageTitle = $scope.job.position_title;
                    $scope.jobId = $scope.job.id;
                    deferred.resolve(data);
                });
            return deferred.promise;
        }

        if ($routeParams.id) {
            $scope.loadJob();
        }
    }
]);

0 个答案:

没有答案