Unit testing an AngularJS directive that contains $watch() not being compiled

Viewed 4009

I'm currently researching my problem but I thought adding a question here may help as I'm new to AngularJS and even newer to Unit Testing.

I have the current directive that works, it users the $watch() function to track a variable, if the variable is not present a default message is provided, for example "Deleted User Value" ...

angular.module('myModule')


.directive('displayName', function ($transform) {
    return {
        restrict: 'A',
        scope: {
            displayName: '='
        },
        link: function (scope, element) {
            scope.$watch('displayName', function(value){
                if(!value) {
                    element.html($transform('users.profile.deletedUser'));
                } else {
                    element.html(value);
                }
            });
        }
    };
})

;

and I have the following unit test (please note that I have amended this on the advice of Maurice) :

beforeEach(module('myModule'));

beforeEach(inject(function($compile, $rootScope) {
    $scope = $rootScope;
    element = angular.element('<div class="name" display-name="name"></div>');
    $compile(element)($scope);
}));


it('should display the deleted user name', inject(function() {
    $scope.displayName = null;
    element.scope().$apply();
    console.log(element);
    expect(element.html()).toBe('Deleted User Value');

}));

However I am getting the following issue: TypeError: Attempted to assign to readonly property. and the console.log is not being outputted, can anyone advise where I am going wrong? Sorry for my stupidity but I am trying to learn unit testing "on the job" and I am still very new to AngularJS

1 Answers
Related