Angular:在测试指令时,您是否模拟了控制器的依赖关系?

时间:2015-02-05 00:20:01

标签: angularjs unit-testing jasmine

我有一个我正在测试的指令,但它似乎要我声明指令使用的控制器的依赖关系(即$ modal,global ect)这是我需要做的吗?如果是这样,在测试指令时如何模拟控制器的依赖关系?是否与控制器模拟它们的设置相同?

我得到的错误是:

  

测试' pbGoogleAnalyticsManagementList测试:应该调用selectProfile()'失败       错误:[$ injector:unpr]未知提供者:$ modalProvider< - $ modal< - GoogleAnalyticsManagementController

我正在进行的测试是:

describe('pbGoogleAnalyticsManagementList', function () {
    var rootScope, scope, element;
    beforeEach(angular.mock.module('pb.webSites.controllers'));
    beforeEach(angular.mock.module('pb.webSites.directives'));

    beforeEach(inject(function ($rootScope, $compile, $templateCache) {
        $templateCache.put('app/webSites/directives/GoogleAnalyticsManagementList.html', '<div></div>');
        rootScope = $rootScope;
        scope = $rootScope.$new();
        element = angular.element('<pb-google-analytics-management-list data-pb-google-analytics-profile="webSite.googleAnalyticsProfile" data-pb-select-profile="addGoogleAnalyticsProfile(profile)">');
        $compile(element)(scope);
        scope.$digest();
    }));

    describe('test', function () {
        it('should call selectProfile()', function () {
            var elementScope = element.isolateScope();

            spyOn(elementScope, 'selectProfile');
            var data = {
                account: 'account',
                property: 'property',
                profile: 'profile'
            }

            elementScope.profileClick(data.account, data.property, data.profile);
            expect(elementScope.selectProfile).toHaveBeenCalledWith(data.account, data.property, data.profile);
        });
    })

1 个答案:

答案 0 :(得分:0)

事实证明,你确实需要包含控制器的依赖性,但在像我这样的情况下可能会失控。由于我们没有测试控制器的功能,您可以使用$ controllerProvider创建一个新版本的Controller,您的指令需要如下:

beforeEach(angular.mock.module('pb.webSites.controllers', function ($provide, $controllerProvider) {
        $controllerProvider.register('GoogleAnalyticsManagementController', function ($scope) {
            // Controller Mock
        });
    }));