带有 gettextCatalog loadRemote 的 angular1 测试指令

angular1 testing directive with gettextCatalog loadRemote

我正在使用带有 es6 语法的 Angular 1.5.8 和 angular-gettext 多语言支持模块。在我的切换语言指令中,我通过

加载翻译后的内容

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

watch 和 build(通过 gulp)工作正常,一切正常,但是一旦我 运行 gulp test 我收到一个错误:

错误:意外请求:GET assets/languages/sr_RS@cyrillic.json

为了测试我使用业力:

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);
  });

每次我 运行 我的 gulp 测试任务我都会收到上述错误。我猜它发生在编译过程中,因为我的 switchLang 指令试图使用 angular-gettext 模块中的 $http.get 获取外部数据。如何解决?

您需要模拟单元测试时发出的任何外部请求。例如

var $httpBackend;
var mockJson = { }; // You can specify the mocked response for "sr_RS@cyrillic.json" 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/sr_RS@cyrillic.json').respond(mockJson);
}));