当尝试测试使用翻译的服务方法(在测试之外工作正常)时,我收到的是从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'.
答案 0 :(得分:0)
您应该设置用于翻译的语言。我有类似的问题。
translate.use('en');
解决了我的问题。