Testing gears in AngularJS and Testacular

I am using angular-http-auth module which intercepts 401 response. This module passes event:auth-loginRequired if there is a 401 response that can be obtained using $ on (). But how can I check this?

 beforeEach(inject(function($injector, $rootScope) { $httpBackend = $injector.get('$httpBackend'); myApi = $injector.get('myApi'); scope = $rootScope.$new(); spyOn($scope, '$on').andCallThrough(); })); describe('API Client Test', function() { it('should return 401', function() { $httpBackend.when('GET', myApi.config.apiRoot + '/user').respond(401, ''); myApi.get(function(error, success) { // this never gets triggered as 401 are intercepted }); scope.$on('event:auth-loginRequired', function() { // This works! console.log('fired'); }); // This doesn't work expect($scope.$on).toHaveBeenCalledWith('event:auth-loginRequired', jasmine.any(Function)); $httpBackend.flush(); }); }); 
+4
source share
1 answer

Based on your comment, I think you do not need expect($scope.$on).toHaveBeenCalledWith(...); because it ensures that something is really listening for the event.

To claim that an event has been fired, you must prepare everything you need and then complete the action leading to the broadcast of the events. I assume that the specification can be described as follows:

 it('should fire "event:auth-loginRequired" event in case of 401', function() { var flag = false; var listener = jasmine.createSpy('listener'); scope.$on('event:auth-loginRequired', listener); $httpBackend.when('GET', myApi.config.apiRoot + '/user').respond(401, ''); runs(function() { myApi.get(function(error, success) { // this never gets triggered as 401 are intercepted }); setTimeout(function() { flag = true; }, 1000); }); waitsFor(function() { return flag; }, 'should be completed', 1200); runs(function() { expect(listener).toHaveBeenCalled(); }); }); 
+9
source

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


All Articles