How do unit test with angular-translate

后端 未结 11 1856
死守一世寂寞
死守一世寂寞 2020-12-08 09:38

I have uses angular translate from here (http://pascalprecht.github.io/angular-translate/) and it\'s just work fine, but it break my controller\'s unit test whith Error:

相关标签:
11条回答
  • 2020-12-08 10:04

    it's a known issue, please follow the documentation here: unit testing angular

    The solution

    Unfortunately, this issue is caused by the design of angular-translate. To get around these errors, all we can do is to overwrite our module configuration in our test suite, that it doesn't use asynchronous loader at all. When there's no asynchronous loader, there's no XHR and therefore no error.

    So how do we overwrite our module configuration at runtime for our test suite? When instantiating an angular module, we can always apply a inline function which is executed as configuration function. This configuration function can be used to overwrite the modules configuration since we have access to all providers.

    Using the $provide provider, we can build a custom loader factory, which should then be used instead of the static files loader.

    beforeEach(module('myApp', function ($provide, $translateProvider) {
    
      $provide.factory('customLoader', function () {
        // loader logic goes here
      });
    
      $translateProvider.useLoader('customLoader');
    
    }));
    

    Please read more in the above link provided.

    0 讨论(0)
  • 2020-12-08 10:04

    I made a simple mock service for $translate

    $translate=function (translation) {
        return {
          then: function (callback) {
            var translated={};
            translation.map(function (transl) {
              translated[transl]=transl;
            });
            return callback(translated);
          }
        }
      };
    

    Usage example here : https://gist.github.com/dam1/5858bdcabb89effca457

    0 讨论(0)
  • 2020-12-08 10:07

    I encountered this problem with protractor tests. My solution was to mock translations like this:

    angular.module('app')
            .config(function ($translateProvider) {
                $translateProvider.translations('en', {});
                $translateProvider.preferredLanguage('en');
            })
    

    Now no language files are downloaded, no strings get translated and I just test against the string keys in specifications:

    expect(element(by.css('#title')).getText()).toEqual('TITLE_TEXT');
    
    0 讨论(0)
  • 2020-12-08 10:16

    Try putting to test method:

    it('should ...', function() {
        httpMock.when('GET', 'scripts/i18n/locale-en.json').respond({});
        httpMock.expectGET('scripts/i18n/locale-en.json');
        scope.resetForm(); // Action which fires a http request
        httpMock.flush(); // Flush must be called after the http request
    }
    

    See examples from Angular docs

    0 讨论(0)
  • 2020-12-08 10:18

    I use this pattern.

    • ApplicationModule set regular angular-translate config.
    • test code load 'testModule' instead of 'applicationModule'

    // application module .js 
    (function() {
      'use strict'; 
      
      angular
       .module('applicationModule', [
        'ngAnimate',
        'ngResource',
        'ui.router',
        'pascalprecht.translate'
      ])
      .config(['$stateProvider', '$urlRouterProvider', '$translateProvider', '$translatePartialLoaderProvider', config]);
    
      function config($stateProvider, $urlRouterProvider, $translateProvider, $translatePartialLoaderProvider) {
        // set routing ... 
            
        $translateProvider.useStaticFilesLoader({
          prefix: 'i18n/locale-',
          suffix: '.json'
        });
    
        $translateProvider.useMessageFormatInterpolation();
        $translateProvider.fallbackLanguage(['en']);
        $translateProvider
        .registerAvailableLanguageKeys(['en', 'ko'], {
          'en_US': 'en',
          'ko_KR': 'ko'
        })
        .determinePreferredLanguage(navigator.browserLanguage);
    
                
        $translateProvider.addInterpolation('$translateMessageFormatInterpolation');    
        $translateProvider.useSanitizeValueStrategy('escaped');
      }
    
    })();

    // test.module.js
    (function() {
      'use strict';
    
      angular
        .module('testModule', ['applicationModule'])
        .config(['$translateProvider', '$translatePartialLoaderProvider', config])
        .run(['$httpBackend', run]);
    
      function config($translateProvider, $translatePartialLoaderProvider) {
        $translateProvider.useLoader('$translatePartialLoader', {
            urlTemplate: 'i18n/locale-en.json'
        });
        $translatePartialLoaderProvider.addPart('applicationModule');
      }
    
      function run($httpBackend) {
        $httpBackend.when('GET', 'i18n/locale-en.json').respond(200);
      }
    
    })();
    
    
    // someDirective.spec.js
    describe("a3Dashboard", function() {
        beforeEach(module("testModule"))
    
        var element, $scope;
        beforeEach(inject(function($compile, $rootScope) {
            $scope = $rootScope;
            element = angular.element("<div>{{2 + 2}}</div>");
            $compile(element)($rootScope)
        }))
    
        it('should equal 4', function() {
          $scope.$digest();
          expect(element.html()).toBe("4");
        })
    
    })
    
    0 讨论(0)
提交回复
热议问题