$ event.stopPropogation is not an error function in Angularjs Unit Test

I am trying to unit test the function associated with the ngClick directive. At the moment it looks something like we just started in this project, and before I get to this, I want to get some kind of coverage:

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

I unit test as follows:

 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 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(); }); }); 

When Karma runs the test, I get this error:

 TypeError: $event.stopPropagation is not a function. 

Any ideas?

+5
source share
2 answers

Your problem is that there is no stopPropagation method in $broadcasted . Broadcast propagates down and stopPropagation (available in $emit ) is used to prevent further propagation up. So you have 2 options.

Use $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(); }); 

Or just create a mock object for the event.

  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(); }); 

Also note that you really don't need to test expect(event.defaultPrevented).toBeTruthy(); or expect(event).toBeDefined(); , because this is the main functionality of angular when calling the preventDefault method and has already been tested.

+9
source

Instead of using stopPropagation (), you can use return false. stopPropagation is a jQuery method, so it should be used for jQuery objects.

This should get the same desired effect:

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

Source: https://habr.com/ru/post/1205293/


All Articles