如何使用 angular-translate 进行单元测试 [英] How do unit test with angular-translate

查看:19
本文介绍了如何使用 angular-translate 进行单元测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从这里使用了角度翻译(http://pascalprecht.github.io/angular-translate/) 并且它工作正常,但它破坏了我的控制器的单元测试,错误:

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:

Unexpected request: GET scripts/i18n/locale-en.json

我不明白为什么?

我使用 yeoman 并使用 karma 进行测试.

I use yeoman and test with karma.

app.js:

'use strict';

(function() {

  angular.module('wbApp', ['authService', 'authUserService', 'checkUserDirective', 'ui.bootstrap', 'pascalprecht.translate'])
    .config(function($routeProvider) {
      $routeProvider
        .when('/', {
          templateUrl: 'views/login.html',
          controller: 'LoginCtrl',
          access: {
            isFree: true
          }
        })
        .when('/main', {
          templateUrl: 'views/main.html',
          controller: 'MainCtrl',
          access: {
            isFree: false
          }
        })
        .otherwise({
          redirectTo: '/'
        });
    });

})();

configTranslate.js:

configTranslate.js:

'use strict';

(function() {

  angular.module('wbApp')
    .config(['$translateProvider',
      function($translateProvider) {

        $translateProvider.useStaticFilesLoader({
            prefix: 'scripts/i18n/locale-',
            suffix: '.json'
        });

        $translateProvider.preferredLanguage('en');

      }]);

})();

karma.conf.js:

karma.conf.js:

files = [

  ...

  'app/bower_components/angular-translate/angular-translate.js',
  'app/bower_components/angular-translate-loader-static-files/angular-translate-loader-static-files.js',

  ...

];

控制器测试:

'use strict';

describe('Controller: LoginCtrl', function() {

  // load the controller's module
  beforeEach(module('wbApp'));

  var LoginCtrl, scope, location, httpMock, authUser;

  // Initialize the controller and a mock scope
  beforeEach(inject(function($controller, $rootScope, $location, $httpBackend, AuthUser) {
    authUser = AuthUser;
    location = $location;
    httpMock = $httpBackend;
    scope = $rootScope.$new();

    LoginCtrl = $controller('LoginCtrl', {
      $scope: scope
    });


    httpMock.when('GET', 'scripts/i18n/locale-en.json').passThrough();

  }));

  it(...);

  ...

});

如果我在测试控制器中添加这个,产品同样的错误:

if i add this in test controller, product same error:

httpMock.when('GET', 'scripts/i18n/locale-en.json').respond(200);
httpMock.flush();

httpMock.when('GET', 'scripts/i18n/locale-en.json').passThrough();
httpMock.flush();

我找到了这篇文章 如何使用在 App Config 中初始化的 Angular Translate 来测试控制器? 但对我没有帮助:/

i find this post How do I test controllers with Angular Translate initialized in App Config? but not helped me :/

我在我的测试中广泛使用 $httpBackend 并且它工作正常,但在这种情况下它是无效的.如果我评论该行:

I extensively use $httpBackend in my tests and it works fine, but in this case it is ineffective. If I comment the line:

$translateProvider.preferredLanguage('en');

显然是一个错误,如果我添加运行时(在我的控制器中)

obviously an error, if I add on the runtime (in my controllers)

$translate.uses(local);

我最终遇到了同样的错误?

I end up with the same error?

所以我转向翻译配置(configTranslate.js)或者在运行时是相同的结果:

So I turn to the translation configuration (configTranslate.js) or at runtime is the same result:

Unexpected request: GET scripts/i18n/locale-en.json

这是我测试的语法,无论是在beforeEach(inject(function(...});"中)

Here is the syntax that I tested, either in a "beforeEach(inject(function(...});"

或者在测试中it('...', function() {...});"

or in a test "it('...', function() {...});"

httpMock.expectGET('scripts/i18n/locale-en.json');
httpMock.when('GET', 'scripts/i18n/locale-en.json').passThrough();
httpMock.when('GET', 'scripts/i18n/locale-en.json').respond(data);

以结尾

httpMock.flush();

我也试过 $ apply

I also tried a $ apply

httpMock.expectGET('scripts/i18n/locale-fr.json');
scope.$apply(function(){
  $translate.uses('fr');
});
httpMock.flush();

什么也没发生,这个错误仍然让我发疯..

nothing happens, Still this error is driving me crazy ..

如果你有什么建议

推荐答案

这是一个已知问题,请按照此处的文档进行操作:单元测试角度

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

解决办法

不幸的是,这个问题是由设计引起的角度翻译.为了解决这些错误,我们所能做的就是在我们的测试套件中覆盖我们的模块配置,它不会完全使用异步加载器.当没有异步加载器时,没有 XHR,因此没有错误.

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.

那么我们如何在运行时为我们的模块覆盖我们的模块配置?测试套件?在实例化一个 angular 模块时,我们总是可以应用作为配置函数执行的内联函数.这个配置函数可用于覆盖模块配置,因为我们可以访问所有提供程序.

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.

使用 $provide 提供程序,我们可以构建自定义加载器工厂,然后应该使用它而不是静态文件加载器.

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.

这篇关于如何使用 angular-translate 进行单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆