Angular-Jasmine将服务注入测试

时间:2016-06-09 20:57:44

标签: angularjs jasmine

Jasmine的新手,我试图实例化我的控制器,它有一个依赖列表(主要是我写的服务)和我尝试过的所有不同的方法都不对。

这是我的控制器:

(function () {
'use strict';

angular.module('app.match')
        .controller('MatchController', MatchController);


MatchController.$inject = ['APP_CONFIG', '$authUser', '$http', '$rootScope', '$state', '$stateParams', 'SearchService', 'ConfirmMatchService', 'MusicOpsService', 'ContentOpsService', 'MatchstickService', 'MatchService', 'Restangular'];
function MatchController(APP_CONFIG, $authUser, $http, $rootScope, $state, $stateParams, searchService, confirmMatchService, musicOpsService, contentOpsService, matchstickService, matchService, Restangular) {

    var vm = this;
    vm.greeting = '';
   .
   .
)();

这是我的测试      (功能(){     'use strict';

describe('app module', function() {
    var MatchController;

    //beforeEach(module('app.match'));
    beforeEach(function($provide) {
        module = angular.module('app.match');
        $provide.service('SearchService', function(){

        });
    });
    beforeEach(module('app.config'));
    beforeEach(module('auth'));


    beforeEach(inject(function($controller, APP_CONFIG, $authUser, $http, $rootScope, $state, $stateParams) {


        MatchController = $controller('MatchController', {'APP_CONFIG':APP_CONFIG, '$authUser':$authUser, '$http':$http, '$rootScope':$rootScope, '$state':$state, '$stateParams':$stateParams, '$provide':$provide});

    }));

    describe("Match controller", function() {

        it("should be created successfully", function() {
            expect(MatchController).toBeDefined();
        });
    });
  });

})();

以上方式运行测试会出现以下错误:

TypeError: 'undefined' is not a function (evaluating  '$provide.service('SearchService', function(){
            })')

1 个答案:

答案 0 :(得分:2)

尝试像这样注入SearchService,而不是使用beforeEach

describe('app module', function() {
var MatchController, SearchService;

beforeEach(module('app.match'));
beforeEach(module('app.config'));
beforeEach(module('auth'));


beforeEach(inject(function($controller, APP_CONFIG, $authUser, $http, $rootScope, $state, $stateParams, _SearchService_) {

    SearchService = _SearchService_;

    MatchController = $controller('MatchController', {
        'APP_CONFIG':APP_CONFIG,
        '$authUser':$authUser,
        '$http':$http,
        '$rootScope':$rootScope,
        '$state':$state,
        '$stateParams':$stateParams,
        '$provide':$provide,
        'SearchService': _SearchService_
    });

}));

describe("Match controller", function() {

    it("should be created successfully", function() {
        expect(MatchController).toBeDefined();
    });
});
});
})();

同样,您也必须注入您的控制器所依赖的其他服务。