Search code examples
jqueryangularjsangularjs-directivejasminemagnific-popup

Unit testing angular directive that wraps jquery lib


I have a small angular app that displays lightboxes. I didn't find anything appropriate (look good on mobile) made for angular, so I settled on magnific-popup. Magnific popup uses jquery to initialize popups:

$(document).ready ->
  $('.image-link').magnificPopup({type:'image'})

I have written a minimal directive which I use to get this working with angular:

angular.module('myapp').directive 'magnificHelper', ($timeout) ->
  restrict: 'A'
  link: (scope, element, attr) ->
    if (scope.$last == true)
      $timeout ->
        element.parent().find('.image-link').magnificPopup
          type:'image'
          gallery: {enabled: true}

This works well, but I am unsure how to write a unit test for this code. I have tried to find an answer online and I guess this must be a fairly common problem, but I didn't find any relevant solutions.


Solution

  • It depends on what you want to test, a basic test could check if $last is defined, e.g.:

    'use strict';
    describe('magnificHelper', function() {
      var $compile,$rootScope, $scope,$timeout, template;
    
      beforeEach(module('myapp'));
    
      beforeEach(inject(function($injector) {
        $rootScope = $injector.get('$rootScope');
        $timeout = $injector.get('$timeout');
        $compile = $injector.get('$compile');
        $scope = $rootScope.$new();
        template = $compile("<div magnificHelper> </div>")($scope);
        $scope.$digest();
      }));
    
      /*
       *
       * Tests
       *
       */
      describe('Test something', function() {
        it('should test something', function() {
          expect(template).toBeDefined()
          expect($scope.last).toBeDefined()
        });
      });
    });
    

    I guess that you can also do something like $scope.magnificPopup = element.parent().find('.image-link').magnificPopupand then inside your test check the $scope.magnificPopup value