2

我有一個處理事件點擊的指令(限制A),並根據一個值調用服務。單元測試期望SpyOn未找到

指令:

define(function() { 
'use strict'; 

var myDirective = function ($rootScope, myFactory) { 
    return { 
     restrict: 'A', 
     scope: { 
      _myValue : '=value' 
     }, 
     link: function(scope, element, attrs) { 
      element.bind('click', function() { 
       if (scope._myValue === 'red') { 
        myFactory.red(); 
       } 
       if (scope._myValue === 'green') { 
        myFactory.green(); 
       } 
       if (scope._myValue === 'black') { 
        myFactory.black(); 
       } 
      }); 
     } 
    }; 
}; 

return ['$rootScope', 'myFactory', myDirective]; 
}); 

測試:

define(['angular-mocks'], function() { 
'use strict'; 

var angular = require('angular'); 

describe('<-- Directive Spec ------>', function() { 

    var scope, $compile, element, myFactory; 

    beforeEach(angular.mock.module('myApp')); 

    beforeEach(inject(function (_$rootScope_, _$compile_, _myFactory_) { 
     scope = _$rootScope_.$new(); 
     $compile = _$compile_; 
     var html = '<div><a my-directive value="\'red\'"></a></div>'; 
     myFactory = _myFactory_; 
     spyOn(myFactory , 'red').and.callThrough(); 
     element = $compile(angular.element(html))(scope); 
     scope.$digest(); 

    })); 

    it('should be red and call myFactory.red', function() { 
     element.click(); 
     expect(myFactory.red).toHaveBeenCalled(); 
    }); 

通過上述,我得到錯誤:

Expected spy red to have been called. 

進出口使用茉莉花2

回答

1

您點擊<div>,而不是<a>,它具有指令和事件處理程序。做:

element.find('a').click(); 

或者乾脆從編譯的HTML中刪除<div>

+0

Doh!非常感謝你 –