When attempting to test a service method that uses a translation (which works fine outside of the test) I am receiving the key I pass in back from TranslateService instead of the translation.
Service being tested (simplified for easiest error recreation):
// 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);
}
}
The test itself:
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'.
});
Hopefully I did't miss any brace or semi-colon in the shortened code above, assuming I did not if you run this test the first one will pass, and the second one will return the failure:
Expected 'settings-page.page-name' to equal 'Settings'.