5

I am building an angular app using material design. I am using $mdSidenav service to play with a sidenav which should be able to open and close along with user desires.

I have created a wrapper service around it like this:

(function () {
  'use strict';

  angular
    .module('app.layout')
    .factory('navigationService', navigationService);

  navigationService.$inject = ['$mdSidenav'];

  function navigationService($mdSidenav) {
    var factory = {};        
    factory.toggle = toggle;
    return factory;

    //////////

    function toggle() {
      $mdSidenav('left').toggle();
    }
  }
}());

So far so good and it works fine. The issue comes when I try to write my unit tests for it using Jasmine. I usually create stubs or spies to mock my dependencies but I cannot get it done with this $mdSidenav due to the odd way to use it: $mdSidenav(sidenav-id).

Usually, with Jasmine in order to spy you need and object and the function you want to mock to spy on it. I have tried several different possibilities with any luck.

What I aim is something similar to:

beforeEach(module(function ($provide) {
  mdSidenav = {};
  mdSidenav.toggle = jasmine.createSpy();
  $provide.value('$mdSidenav', mdSidenav);
}));

beforeEach(inject(function(_navigationService_) {
  navigationService = _navigationService_;
}));

it('Should call $mdSidenav toggle when required', function() {
    // act
    navigationService.toggle();
    // assert
    expect(mdSidenav.toggle).toHaveBeenCalled();
});

Is there a way to test this?

isherwood
  • 58,414
  • 16
  • 114
  • 157
jbernal
  • 785
  • 1
  • 14
  • 29

1 Answers1

6

I'm not familiar with the material design library, but it looks like $mdSidenav returns a function.

Why don't you replace :$provide.value('$mdSidenav', mdSidenav); with

$provide.factory('$mdSidenav', function() { 
      return function(direction){//if you use direction ('left' in your example) you could use it here
                 return mdSidenav;
              };
})
Gustav
  • 3,408
  • 4
  • 24
  • 41
  • 1
    It works! I never thought about making a factory which was actually a function itself. Thanks! :) – jbernal Aug 11 '15 at 17:59