Unit testing form templates with directives returns "Error: [$injector:unpr] Unknown provider:"

271 Views Asked by At

I'm creating a unit test form my form validation. In my main form template controller, I am mocking the injected service. And the form template also contains a directive that injects the same service.

I am using html2js to load my html templates. And it is throwing this error on $compile:

Error: [$injector:unpr] Unknown provider: CommonServiceProvider <- CommonService

Here is how i set my test:

beforeEach(inject(function ($rootScope, $compile, $controller, $q, $filter, $templateCache) {

    //scope instance to use in test cases.
    scope = $rootScope.$new();

    //set mock 
    var _commonService = MockCommonService($q, $filter).CommonService;


    //Inject fake service into controller
    var controller = $controller('PromoCreateGlobalCtrl', {$scope: scope, CommonService: _commonService});


    //for my directive tempalte
    var titleSearchTmplt = $templateCache.get('directives/title-search/title-search.html');
    $templateCache.put('app/directives/title-search/title-search.html', titleSearchTmplt);

    //for my main form template
    var templateHtml = $templateCache.get('promotion/create/global/promo-global-create.html');
    var formElem = angular.element(templateHtml).find('form');


    $compile(formElem)(scope); //error is thrown on this line.

    form = scope.form;

    scope.$apply();

    //directiveElem = getCompiledElement();

}));

How should I load the mock service on the directive's controller? I think that is what causes the issue. Has someone run into same case for testing?

The issue seems to be caused by the CommonService being loaded the second time when I load the directive template. Or there is other cause?

1

There are 1 best solutions below

0
On

you need to inject the service in beforeeach

var CommonService

 beforeEach(inject(function ($rootScope, $compile, $controller, $q, $filter, 
$templateCache,_CommonService_){
CommonService=_CommonService_;}