theSmaw
theSmaw

Reputation: 697

Testing AngularJS directives that directly consume services

I have a directive that makes use of a service:

  MyDirective = (myService) ->

    compile: () ->
      stuff = myService.getStuff()

  MyDirective.$inject = ['MyService']

  app = A.module 'myApp'
  app.directive 'myDirective', MyDirective

I want to be able to test that myService.getStuff is called.

For my tests for controllers, I have been able to do:

angular.mock.inject ($controller) ->
  myController = $controller 'MyController',
    $scope: $scope
    mockMe: mockMethod: () ->
      assert.ok()
      done()

If I do similar with my directive, I get the following error:

angular.mock.inject ($directive) ->
  myDirective = $directive 'MyDirective',
    $scope: $scope
    myService: getStuff: () ->
      assert.ok()
      done()

Error: Unknown provider: $directiveProvider <- $directive

Any ideas how I can get a reference to the directive and inject mocks in to it?

Before all my tests I am doing:

angular.mock.module 'myApp'

I have been able to solve this by going directive -> controller -> service rather than directive -> service. Is that the recommended solution? e.g

$scope.getStuff = (name, success) ->
  assert.ok true
  done()

$_compile(elm) $scope
$scope.$digest()

Upvotes: 3

Views: 2172

Answers (1)

Jesus is Lord
Jesus is Lord

Reputation: 15399

Is this what you're talking about?

var scope, element;

angular.mock.inject(function ($compile, $rootScope) {
    scope = $rootScope;
    element = $compile('<my-directive />')(scope);
    scope.$digest();
});

From here you can make changes to the scope, call $digest() again to see those changes reflected in the element. If myDirective relies on a service myService via injection you'd like to mock, you need to do something like this before you call inject():

module('moduleWithDirective', function ($provide) {
    $provide.provider('myService', {
        $get: function () {
            return { /* service goes here. */ };
        }
    });
});

Upvotes: 2

Related Questions