传递服务依赖注入以进行控制器测试

时间:2016-02-28 13:55:38

标签: angularjs

AllData.js包含以下代码

    var module = angular.module("myApp", []);

    module.service("StoreService", function () {

    this.AddCategory = function (newCategoryToAdd) {
            var categoriesLocal = [];
            $.ajax({
                url: "/Category/Create",
                type: "POST",
                data: "{'newCategoryToAdd' : '" + newCategoryToAdd + "'}",
                contentType: "application/json; charset=utf-8",
                error: function (xhr) {
                    alert('Error: ' + xhr.statusText);
                },
                success: function (result) {
                    categoriesLocal = result;
                },
                async: false

            });
            return categoriesLocal;
        }
    }
module.controller("CategoryController", function ($scope, StoreService) {
});

CategoryControllerFile包含测试代码:

/// <reference path="C:\Programming\New Projects\MVCAngular1App\MVCAngular1App\Scripts/jasmine/jasmine.js" />
/// <reference path="C:\Programming\New Projects\MVCAngular1App\MVCAngular1App\Scripts/angular-mocks.js" />
/// <reference path="C:\Programming\New Projects\MVCAngular1App\MVCAngular1App\Scripts/angular.min.js" />
/// <reference path="C:\Programming\New Projects\MVCAngular1App\MVCAngular1App\Scripts/AllData.js" />

decribe('CategoryControllerTest', function () {
    beforeEach(module('myApp'));
    var $controller, StoreService;

    beforeEach(inject(function (_CategoryController_, _StoreService_) {

        $controller = _CategoryController_;
        StoreService = _StoreService_;

    }));
    describe('$scope.AddCategory', function () {
        it('adds a category', function () {
            var $scope = {};
            var controller = $controller('CategoryController', { $scope: $scope });
            var length = $scope.categories.length;
            $scope.newCategory = "TestCategory";
            $scope.AddCategory($scope.newCategory);
            var newLength = $scope.categories.length;
            expect($scope.categories.length).toEqual(newLength);
        });
    });
});

如何在我的测试方法中将我的服务作为依赖注入注入

我已经编辑了我的代码以显示各自的文件

2 个答案:

答案 0 :(得分:0)

这是您注入服务的方式:

decribe('CategoryControllerTests', function(){
    beforeEach(module('myApp'));

    var $controller, StoreService ;

    beforeEach(inject(function (_$controller_, _StoreService_) {

        $controller = _$controller_;
        StoreService = _StoreService_;

    }));
};

答案 1 :(得分:0)

func tableView(tableView: UITableView,heightForFooterInSection section: Int) -> CGFloat {
     return 1
}

最后它有效!这是正确的代码。