1

As part of an AngualrJS app, I have to retrieve user details from a REST api before bootstrapping the application.

var initInjector = angular.injector(['ng']);
var $http = initInjector.get('$http');

$http.get('../api/user').then(
  function (response) {
    if (response.user.valid) {
      angular.bootstrap(document, ['app']);
    }
  },
  function () {
    window.location.href = '../userError.html';
  }
});

I'm building the application using gulp, and have been trying to unit test this as follows

describe('unit test app config', function () {
  beforeEach(function () {
    module('app');
    inject();
  });

  it('should log a message on calling the injector', function () {
    spyOn(angular, 'injector').and.callThrough();
    expect(angular.injector).toHaveBeenCalled();
  });
});

but this is giving the following error: Expected spy injector to have been called.

How can I unit test this code? I just need to mock the $http service and test the success and failure functions

Joseph McCarthy
  • 897
  • 2
  • 19
  • 41
  • angularjs services will be available until after it is bootstraped. So trying to use `$http` etc is futile at best. However you can use 2 apps - bootstrap the first one to perform /api/user stuff and then bootstrap your main application. But none of that complexity is necessary and you can take care of all within one single application with proper usage of run blocks and/or route resolvers. But your question is not asking that so I can't answer that here. – bhantol Jan 23 '18 at 15:54

0 Answers0