如何向茉莉花注入服务

时间:2015-05-30 15:12:24

标签: angularjs unit-testing jasmine karma-runner karma-jasmine

我有以下测试用例MeetingCtrlSpec.js

describe('ViewMeetingCtrl', function () {
        var $rootScope, scope, $controller   ;

       beforeEach(angular.mock.module('MyApp'));

       beforeEach(inject(function ($rootScope, $controller  ) {
            scope = $rootScope.$new();
            $controller('ViewMeetingCtrl', {
            $scope: scope,
           }); 
        }));

        it('should change greeting value if name value is changed', function () {
            //some assertion
        });
    });

ViewMeetingCtrl.js

(function () {
    'use strict';
    angular.module('MyApp').controller('ViewMeetingCtrl', ViewMeetingCtrl);

    ViewMeetingCtrl.$inject = ['$scope', '$state', '$http', '$translate', 'notificationService', 'meetingService', '$modal', 'meeting', 'attachmentService'];

    function ViewMeetingCtrl($scope, $state, $http, $translate, notificationService, meetingService, $modal, meeting, attachmentService) {
        $scope.meeting = meeting;                    
        //more code goes here
    }
})();

会议来自app.routes.js文件

.state('company.meeting', {
                abstract: true,
                url: '/meetings/:meetingId',
                template: '<ui-view/>',
                resolve: {
                    meeting: function(meetingService, $stateParams){
                        return meetingService
                                .getMeeting($stateParams.meetingId)
                                .then(function(response){
                                    return response.data;
                                });
                    }
                },
            })

我的问题是关于在此ctrl中注入会议。我不确定如何在我的测试用例中注入它。我确实喜欢以下内容。

describe('ViewMeetingCtrl', function () {
            var $rootScope, scope, $controller , meeting   ;

           beforeEach(angular.mock.module('MyApp'));

           beforeEach(inject(function ($rootScope, $controller , meeting     ) {
                scope = $rootScope.$new();
                $controller('ViewMeetingCtrl', {
                $scope: scope,
                meeting : meeting   
               }); 
            }));

            it('should change greeting value if name value is changed', function () {
                //some assertion
            });
        });

...我收到此错误Error: [$injector:unpr] Unknown provider: meetingProvider <- meeting

如何将会议依赖关系注入我的测试用例。 ?

1 个答案:

答案 0 :(得分:1)

Meeting不是服务,而是在路由解析时注入的对象。在测试用例中,您应该显式创建meeting虚拟对象。

 beforeEach(inject(function ($rootScope, $controller,$q ) {
                scope = $rootScope.$new();

                $controller('ViewMeetingCtrl', {
                $scope: scope,
                meeting : {}  //your custom object
               }); 
            })); 

请记住,您在测试中测试控制器而不是路径分辨率注入。