How do I test angularjs directive to spy on the function call?

后端 未结 2 773
轮回少年
轮回少年 2021-02-08 04:03

Code below executes but complains about element.popover not being invoked. I can\'t seem to figure out what the issue is.

Thanks for help in advance.

dir

2条回答
  •  滥情空心
    2021-02-08 04:54

    I got it to work.
    jquery and jquery popover js files need to be loaded before angular.js during the test. This order should be specified in the testacular.conf.js file. Also, the url for http was missing ‘/’. Here is the code that is working for me:


    angular.module('directives', []).
    
    directive('popOver', function($http) {
    
      return {
        restrict: 'C',
    
        link: function(scope, element, attr) {
          element.bind('mouseover', function(e) {
            $http.get("someurl/" + attr.chatid + ".json").success(function(data) {
              element.popover({
                content: data.firstName + " " + data.lastName
              });
            });
          });
        }
      }
    })
    
    
    
    'user strict'
    
    describe('directives', function() {
      beforeEach(module('directives'));
      describe('popOver', function() {
        var $scope, compile, location, $httpBackend, elm;
    
        beforeEach(inject(function($rootScope, $compile, _$httpBackend_) {
          $scope = $rootScope.$new();
          compile = $compile;
          $httpBackend = _$httpBackend_;
          elm = angular.element(' ');
          compile(elm)($scope);
    
        }));
    
        it('should call element.popover()', function() {
          $httpBackend.expectGET('someurl/testChatId.json').
          respond([{
            firstName: 'test',
            lastName: 'user'
          }]);
          //spyOn(elm, 'popover').andCallThrough();
          spyOn($.fn, 'popover').andCallThrough();
    
          elm.trigger('mouseover');
          $httpBackend.flush();
    
          //expect(elm.popover).toHaveBeenCalled();
          expect($.fn.popover).toHaveBeenCalled();
        });
      });
    });
    

提交回复
热议问题