Search code examples
angularjskarma-jasmineangularjs-e2e

angular1 testing directive with gettextCatalog loadRemote


I am using Angular 1.5.8 with es6 syntax and angular-gettext module for multilanguage support. In my switch-language directive I load translated content via

this.gettextCatalog.loadRemote(`assets/languages/${this.LanguageService.currentLanguage}.json`);

watch and build (via gulp) works fine, everything is as it should be, but once I run gulp test I receive an error:

Error: Unexpected request: GET assets/languages/[email protected]

For testing I use karma:

beforeEach(inject(($compile, $rootScope) => {

    element = angular.element(`
      <lang-switcher></lang-switcher>
    `);

    $compile(element)($rootScope.$new());
    $rootScope.$digest();
    vm = element.isolateScope().vm;
  }));

  it('should be compiled', () => {
    expect(element.html()).not.toEqual(null);
  });

each time i run my gulp test task I receive the above error. I guess it happens during compile process since my switchLang directive tries to get external data using $http.get from angular-gettext module. How this can be solved?


Solution

  • You will need to mock any external requests that are made when unit testing. e.g.

    var $httpBackend;
    var mockJson = { }; // You can specify the mocked response for "[email protected]" if necessary
    
    beforeEach(inject(($compile, $rootScope, $httpBackend) => {
        element = angular.element(`
            <lang-switcher></lang-switcher>
        `);
    
        $compile(element)($rootScope.$new());
        $rootScope.$digest();
        vm = element.isolateScope().vm;
    
        $httpBackend.when('GET', 'assets/languages/[email protected]').respond(mockJson);
    }));