角度测试stateprovider始终返回null

时间:2017-03-07 08:09:20

标签: angularjs jasmine

我使用Karma编写角度测试:这是我的spec.js文件:

'use strict';
var state;
var $rootScope, $state, $injector, CategoriesService;

describe('Categories', function() {
describe('Categories Manage', function() {

    beforeEach(function() {
       beforeEach(module('ui.router'));
       module('CL.Categories', function($provide) {
            $provide.value('CategoriesService', CategoriesService = {});
        });

        inject(function(_$rootScope_, _$state_, _$injector_, $templateCache, _CategoriesService_) {
            $rootScope = _$rootScope_;
            $state = _$state_;
            $injector = _$injector_;
            CategoriesService = _CategoriesService_;

            // We need add the template entry into the templateCache if we ever
            // specify a templateUrl
            $templateCache.put('layout/dashboard.html', '');
            $templateCache.put('layout/sidebar.html', '');
            $templateCache.put('layout/footer.html', '');
            $templateCache.put('layout/header.html', '');
            $templateCache.put('categories/manage/index.html', '');

        });
    });

    it('should respond to URL with query parameters', function() {
        expect($state.href(state)).toEqual('#/categories/manage');
    });
});

});

这是我的配置文件:

(function (){
'use strict';

angular.module('CL.Categories')
    .config(['$stateProvider', categoriesConfig]);

function categoriesConfig ($stateProvider){
    $stateProvider
        .state('dashboard.selectCategories', {
            url: "/categories/select?criteria&referrer&index",
            templateUrl: 'categories/select/index.html',
            controller: 'SelectCategoriesController',
            controllerAs: 'vm',
            resolve: {
                categoryRoot: ['CategoriesService', function(CategoriesService){
                    return CategoriesService.getRootCategories();
                }]
            }
        })
        .state('dashboard.manageCategories', {
            url: "/categories/manage?active",
            templateUrl: 'categories/manage/index.html',
            controller: 'ManageCategoriesController',
            controllerAs: 'vm',
            resolve: {
                workCategories: ['CategoriesService', function (CategoriesService) {
                    return CategoriesService.getCategoriesByOrganisationWithCertificates();
                }]
            }
        });
}
})();

在我的karma.config文件中,我将基本路径设置为' ./' 。测试期望($ state.href(state))总是返回null

1 个答案:

答案 0 :(得分:0)

当你在模拟国家电话时,试试这个以获得“州”:

state = $state.get('dashboard.selectCategories');

然后你可以测试状态声明的部分:

expect(state.url).toEqual('/categories/select?criteria&referrer&index');
expect(state.templateUrl).toEqual('categories/select/index.html');

等等......