1

当尝试测试使用翻译的服务方法(在测试之外工作正常)时,我收到了从 TranslateService 传回的密钥,而不是翻译。

正在测试的服务(为最简单的错误重现而简化):

// The proper imports are here.

@Injectable()
export class SiteHeaderService {
  private _titleText: BehaviorSubject<string> = new BehaviorSubject("");
  public readonly titleText: Observable<string> = this._titleText.asObservable();

  constructor(private translateService: TranslateService) {}

  public updateTitleTextValue(text: string) {
    this._titleText.next(text);
  }

  public setSettingsPageTitle() {
    const title = this.translateService.instant("settings-page.page-name") || "";
    this.updateTitleTextValue(title);
  }
}

测试本身:

import { TestBed, inject } from "@angular/core/testing";

import { SiteHeaderService } from "../site-header.service";

import { Http } from "@angular/http";
import { TranslateLoader, TranslateModule, TranslateStaticLoader } from "ng2-translate";

describe("SiteHeaderService", () => {
  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [ TranslateModule.forRoot({
        provide: TranslateLoader,
        useFactory: (http: Http) => new TranslateStaticLoader(http, 'base/i18n', '.json'),
        deps: [ Http ]
      }) ],
      providers: [ SiteHeaderService ]
    });
  });

  it("should update the _titleText subject with the given value", inject([SiteHeaderService], (service: SiteHeaderService) => {
    service.updateTitleTextValue("Firefly was canceled too soon!");
    service.titleText.subscribe( title => { expect(title).toEqual("Firefly was canceled too soon!"); } )
  }));  // Passes

  it("should update all subjects to their 'settings page' state", inject([SiteHeaderService], (service: SiteHeaderService) => {
    service.setSettingsPageTitle();
    service.titleText.subscribe( title => { expect(title).toEqual("Settings"); } )
  }));  // Fails: Expected 'settings-page.page-name' to equal 'Settings'.

});

希望我没有错过上面缩短的代码中的任何大括号或分号,假设我没有如果你运行这个测试,第一个将通过,第二个将返回失败:

Expected 'settings-page.page-name' to equal 'Settings'.
4

1 回答 1

-2

您应该设置用于翻译的语言。我有类似的问题。

translate.use('en');

解决了我的问题。

于 2017-12-04T15:10:37.097 回答