TypeError: parsed undefined on angularjs unit test service

I am trying to do a unit test for a service that uses $ http. I am using Jasmine and I keep getting this error:

TypeError: parsed undefined in angular.js (line 13737)

This is what my service looks like:

angular.module('myapp.services', []) .factory('inviteService', ['$rootScope', '$http', function($rootScope, $http) { var inviteService = { token: '', getInvite: function(callback, errorCallback) { $http.get('/invites/' + this.token + '/get-invite') .success(function(data) { callback(data); }) .error(function(data, status, headers, config) { errorCallback(status); }); } }; return inviteService; }]); 

This is what my test looks like:

 describe ('Invite Service', function () { var $httpBackend, inviteService, authRequestHandler; var token = '1123581321'; beforeEach(module('myapp.services')); beforeEach(inject(function ($injector) { $httpBackend = $injector.get('$httpBackend'); authRequestHandler = $httpBackend.when('/invites/' + token + '/get-invite').respond({userId: 'userX'}, {'A-Token': 'xxx'}); inviteService = $injector.get('inviteService'); })); afterEach (function () { $httpBackend.verifyNoOutstandingExpectation (); $httpBackend.verifyNoOutstandingRequest (); }); describe ('getInvite', function () { beforeEach(function () { inviteService.token = token; }); it ('should return the invite', function () { $httpBackend.expectGET('/invites/' + token + '/get-invite'); inviteService.getInvite(); $httpBackend.flush(); }); }); }); 

I am new to angularjs based unit testing applications and I used this example in angularjs documentation

https://docs.angularjs.org/api/ngMock/service/ $ httpBackend

I'm not sure what I could lose, and I have already tried different things, and I always get the same error, any help would be appreciated.

+5
source share
1 answer

The parsed variable is the URL of the corresponding service. It is undefined for one of the following reasons:

  • Invalid URL
  • $ http.get is not called
  • token not defined
  • sucess and error callbacks do not have data
  • .respond not called
  • .respond does not include the response object as an argument

For instance:

  describe('simple test', test); function test() { it('should call inviteService and pass mock data', foo); function foo() { module('myapp.services'); inject(myServiceTest); function myServiceTest(inviteService, $httpBackend) { $httpBackend.expect('GET', /.*/).respond(200, 'bar'); function callback(){}; inviteService.getInvite.token = '1123581321'; inviteService.getInvite(callback, callback); $httpBackend.flush(); expect(callback).toHaveBeenCalledOnce(); } } } 

References

+6
source

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


All Articles