2014-10-22 2 views
5

ngClick 지시문에 바인딩 된 함수를 단위 테스트하려고합니다. 우리가이 프로젝트를 시작했습니다 그것은 지금은 이런 걸보고 내가 멀리에 도착하기 전에 나는 몇 가지 테스트 적용하려면이 같은

vm.open = function($event) { 
      $event.preventDefault(); 
      $event.stopPropagation(); 
      vm.opened = true; 
     }; 

I 단위 테스트 :

describe('Unit: simpleSearchController', function(){ 
//include main module 
beforeEach(module('myApp')); 
var ctrl, scope, event ; 
// inject the $controller and $rootScope services 
// in the beforeEach block 
beforeEach(inject(function($controller, $rootScope){ 
    // Create a new scope that's a child of the $rootScope 
    scope = $rootScope.$new(); 
    // Create the controller and alias access using controllerAs 
    ctrl = $controller('simpleSearchController as vm', { 
     $scope: scope 
    }); 
})); 
// unit tests 
it('should set vm.opened to true', function(){ 
    event = scope.$broadcast("click"); 
    expect(event).toBeDefined(); 
    scope.vm.open(event); 
    expect(event.defaultPrevented).toBeTruthy(); 
    expect(scope.vm.opened).toBeTruthy(); 
}); 
}); 

카르마를 이 오류가 발생하는 테스트를 실행합니다.

TypeError: $event.stopPropagation is not a function. 

아이디어가 있으십니까?

+0

'$ ($ event) .stopPropagation();'시도 했습니까? – algorhythm

+2

이벤트를 브로드 캐스트 할 때 전파 전파가 제대로되지 않습니까? 방송이 중단되면 stopPropagation이 방출됩니다. $ emit을 사용해 보셨습니까? 또는 그냥 모의 이벤트 객체를 만들고 메소드에 대해 스파이를 수행하면됩니다. 'expect (event.defaultPrevented) .toBeTruthy();를 테스트 할 필요가 없습니다. 이미 각도 코어의 일부로 테스트되었습니다. – PSL

+0

당신은 정확한 @PSL입니다. 답변으로 추가하십시오. –

답변

9

귀하의 문제는 $broadcasted 이벤트에는 stopPropagation 방법이 없다는 것입니다. 브로드 캐스트가 전파되고 stopPropagation ($emit)이 더 이상 전파되지 않도록 사용됩니다. 그래서 2 가지 옵션이 있습니다.

하나는 $emit

it('should set vm.opened to true', function(){ 
     event = scope.$emit("click"); 
     expect(event).toBeDefined(); 
     scope.vm.open(event); 
     expect(event.defaultPrevented).toBeTruthy(); 
     expect(scope.vm.opened).toBeTruthy(); 
    }); 

를 사용하거나 이벤트에 대한 모의 개체를 만듭니다.

it('should set vm.opened to true', function(){ 
      event = jasmine.createSpyObj('event', ['preventDefault', 'stopPropagation']); 
      scope.vm.open(event); 
      expect(event.preventDefault).toHaveBeenCalled(); 
      expect(scope.vm.opened).toBeTruthy(); 
     }); 

또한이로 preventDefault라고하며 이미 테스트 된 경우 핵심 각 기능이기 때문에 당신이 정말로 expect(event.defaultPrevented).toBeTruthy(); 또는 expect(event).toBeDefined();을 테스트 할 필요는 없습니다.

0

stopPropagation() 대신 return false를 사용할 수 있습니다. stopPropagation은 jQuery 메서드이므로 jQuery 객체에 사용해야합니다.

이 같은 원하는 효과를 얻을해야합니다

vm.open = function($event) {    
     vm.opened = true; 
     return false 
    }; 
+0

이것은 각도가 아니며 반환 값을 찾지 않습니다. 그것은 비록 OP에서 오류를 억제합니다. OP가 잘못하고있다. – PSL

+0

@JohnStewart 테스트가 통과합니다. :)하지만 이것은 jquery 이벤트가 아닙니다. 이것은 각도로 작성된 맞춤 이벤트입니다. 테스트 자체가 올바르지 않습니다. – PSL

+0

정확합니다. http://stackoverflow.com/questions/1357118/event-preventdefault-vs-return-false –

관련 문제