Testing

Unit testing an AngularJS directive's private functions.

Posted on by  
Richard Rijnberk

As we all know Javascript gives us the awesome ability to create functions inside functions. This allows us to create private functions which support the main function. It is also something we do often when creating object functions. This structure is used by angular for the creation of providers and directives alike. Every once in a while I personally come to a point where I would like to test these private functions. This is especially true for use cases in Angular such as directives.I'd like to be able to run unit tests for a directive's private functions, but I'd like to do this without having to make them public. The way I do this is by using a concept called reflection. This process actually described by Bob Gravelle in his post 'Accessing Private functions in Javascript' actually exposes the private functions by using the toString method of a function. Before I go into specifics let me say that this article should only be used as an approach  for unit testing. There is a good reason for keeping private functions private and using this concept for application code may very well introduce interesting side effects. That being said let's go into details. In order for us to use this concept we'll need to make some slight changes to our directive. Normally we would declare our Directive Definition Object (DDO) and directly return it. As below:

return {
  restrict: 'E'
  ...
}

Continue reading →

shadow-left