Despite extensive research, I have struggled to successfully test an Angular directive due to the inability to access functions within its controller.
Here is the snippet of the directive code:
angular.module('app').
directive("accordionItem", function () {
return{
restrict: 'E',
replace: true,
templateUrl: function (elem, attr) {
return 'partials/invoice/' + attr.temp + '.html';
},
scope: {
invoice: '=',
temp: '@'
},
controller: function ($scope, listSelectionService, $state) {
$scope.selectItem = function () {
if ($scope.isOpen()) {
listSelectionService.selectedItem = -1;
}
else {
listSelectionService.selectedItem = $scope.invoice;
}
};
$scope.isOpen = function () {
return listSelectionService.selectedItem === $scope.invoice;
};
$scope.showFaturasSubscription = function () {
$state.go('app.ultimasFaturasSubscription', {subscriptionId: $scope.invoice.subscriptionId});
};
}
};
});
Below is my test script for the directive:
describe('Invoice', function() {
var $scope = {}, controller, $httpBackend, $controller, form, element;
beforeEach(module('app'));
describe('Directives', function() {
beforeEach(inject(function($compile, $rootScope, _$httpBackend_, _$controller_) {
$httpBackend = _$httpBackend_;
$httpBackend.expect('GET', 'data/translation/?lang=pt').respond(200, []);
$httpBackend.when('GET', 'partials/invoice/undefined.html').respond(200, []);
$httpBackend.when('GET', 'partials/templates/loading.html').respond(200, []);
$httpBackend.when('GET', 'partials/invoice/invoiceContent.html').respond(200, []);
$scope = $rootScope.$new();
$controller = _$controller_;
form = $compile("<accordion-item temp='invoiceContent'></accordion-item>")($scope);
$scope.$digest();
}));
it('should submitButtonDisabled', inject(function($injector) {
var listSelectionService = $injector.get("listSelectionService");
$scope.selectItem();
expect(listSelectionService.selectedItem).toBe(-1);
}));
});
});
Despite documentation suggesting that we should have access to the controller of the directive after calling $digest(), I am encountering the error message below:
TypeError: $scope.selectItem is not a function at null.<anonymous> (http://localhost:8234/spec/invoice/invoiceDirectivesSpec.js:27:20) ... Error: Declaration Location ...
I would greatly appreciate any assistance with this issue.