Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit testing a directive that defines a controller in AngularJS

I'm trying to test a directive using Karma and Jasmine that does a couple of things. First being that it uses a templateUrl and second that it defines a controller. This may not be the correct terminology, but it creates a controller in its declaration. The Angular application is set up so that each unit is contained within its own module. For example, all directives are included within module app.directive, all controllers are contained within app.controller, and all services are contained within app.service etc.

To complicate things further, the controller being defined within this directive has a single dependency and it contains a function that makes an $http request to set a value on the $scope. I know that I can mock this dependency using $httpBackend mock to simulate the $http call and return the proper object to the call of this function. I've done this numerous times on the other unit tests that I've created, and have a pretty good grasp on this concept.

The code below is written in CoffeeScript.

Here is my directive:

    angular.module('app.directive')
      .directive 'exampleDirective', [() ->
        restrict: 'A'
        templateUrl: 'partials/view.html'
        scope: true
        controller: ['$scope', 'Service', ($scope, Service) ->
          $scope.model = {}
          $scope.model.value_one = 1

          # Call the dependency
          Service.getValue()
            .success (data) ->
              $scope.model.value_two = data
            .error ->
              $scope.model.value_two = 0
        ]
      ]

Here is the dependency service:

    angular.module("app.service")
      .factory 'Service', ['$http', ($http) ->

      getValue: () ->
        options.method = "GET"
        options.url = "example/fetch"

        $http _.defaults(options)

Here is the view:

    <div>
      {{model.value_one}} {{model.value_two}}
    </div>

I've simplified this quite a bit, as my goal is only to understand how to wire this up, I can take it from there. The reason I'm structuring it this way is because I did not initially create this. I'm working on writing tests for an existing project and I don't have the ability to configure it any other way. I've made an attempt to write the test, but cannot get it to do what i want.

I want to test to see if the values are being bound to the view, and if possible to also test to see if the controller is creating the values properly.

Here is what I've got:

    'use strict'

    describe "the exampleDirective Directive", ->

      beforeEach module("app.directive")
      beforeEach module("app/partials/view.html")

      ServiceMock = {
        getValue : () ->

        options.method = "GET"
        options.url = "example/fetch"

        $http _.defaults(options)
      }

     #use the mock instead of the service
     beforeEach module ($provide) ->
       $provide.value "Service", ServiceMock
       return

     $httpBackend = null
     scope = null
     elem = null

     beforeEach inject ($compile, $rootScope, $injector) ->

     # get httpBackend object
     $httpBackend = $injector.get("$httpBackend")
     $httpBackend.whenGET("example/fetch").respond(200, "it works")

     #set up the scope
     scope = $rootScope

     #create and compile directive
     elem = angular.element('<example-directive></example-directive>')
     $compile(elem)(scope)
     scope.$digest()

I don't know how close I am, or if this is even correct. I want to be able to assert that the values are bound to the view correctly. I've used Vojtajina's example to set up html2js in my karma.js file to allow me to grab the views. I've done a lot of research to find the answer, but I need some help. Hopefully a programmer wiser than I can point me in the right direction. Thank you.

like image 924
The Zuidz Avatar asked Jul 12 '13 21:07

The Zuidz


1 Answers

Create the element in karma, then use the .controller() function with the name of your directive to grab the controller. For your example, replace the last couple of lines with these:

elem = angular.element('<div example-directive></div>');
$compile(elem)($rootScope);
var controller = elem.controller('exampleDirective');

Note, that given how you defined your directive, it should be by attribute, and not as an element. I'm also not 100% sure, but I don't think you need the scope.$digest; usually I just put anything that needs to be applied into a scope.$apply(function() {}) block.

like image 164
user2680223 Avatar answered Oct 11 '22 13:10

user2680223