lundi 2 novembre 2015

How to mock services in directive tests?

i have a directive with the injected apiService which is a wrapper around $http and others custom services.

when I try to test the directive, I don't know how to mock the service:

app.directive('coreMenu', ['apiService', function (apiService) {
return {
    restrict    : 'E',
    replace     : true,
    templateUrl : 'Directives/CoreMenu.tpl.html',
    link: function (scope) {
        apiService.get({
            module: 'Core',
            route: 'Menu'
        }).then(function (response) {
            scope.menuItems = response.data;
        }, function (response) {
            // error: no menu available
        });
    }
  };
}]);

Test:

describe('coreMenu directive', function() {
var $compile, $rootScope;

beforeEach(function () {
    module('AdminTechPortal');
    module('CoreLeftMenu.tpl.html');

    inject(function (_$compile_, _$rootScope_) {
        $compile     = _$compile_;
        $rootScope   = _$rootScope_;
    });

it('replaces the element with the appropriate content', function() {
    var element = $compile("<core-menu></core-menu>")($rootScope);
    $rootScope.$digest();

    expect(element.html()).toContain('id="core-menu"');
   });
});

This test throws ( which is normal):

Error: Unexpected request: GET /Core/Menu/

Is it possible to mock apiService and not just the xhr call using $httpbackend ?

Aucun commentaire:

Enregistrer un commentaire