How to unit test ng2 translation using karma jasmine in Angular2

I am trying to translate a page using the German and English variants using ng2-translate.

navbar.component.html

<div id="sidebar-wrapper">     <div class="side-wrap-div">         <div class="list-group sidebar-nav">             <li class="list-group-item borderBottomMenu active" >                 <a href="#">{{ 'PAGE.GENERAL' | translate}}</a>                 <span class="marker-logo"></span>                 <span class="logo allgemein-logo-click" ></span>             </li>         </div>     </div> </div> 

navbar.component.spec.ts

 import { TestBed, ComponentFixture, async } from "@angular/core/testing"; import { DebugElement } from "@angular/core"; import { By } from "@angular/platform-browser"; import { SidenavComponent } from "../sidenav/sidenav.component"; import {TranslateService, TranslateModule} from "ng2-translate"; class TranslateServiceMock {    private lang: string;    public getTranslation() : string {        return this.lang;    } } describe('Navbar Component Test', () => {    let comp: SidenavComponent;    let fixture: ComponentFixture<SidenavComponent>;       beforeEach(async(() => {        TestBed.configureTestingModule({            declarations: [ SidenavComponent ], // declare the test component            providers: [ {provide: TranslateService, useClass: TranslateServiceMock} ]        })            .compileComponents();        fixture = TestBed.createComponent(SidenavComponent);        comp = fixture.componentInstance;    })); it('should have a taskview header', () => {        fixture.detectChanges();        expect("How to test the getTranslation() here????" ).toContain('General');    }) }); 

Translation happens and {{'PAGE.GENERAL' | translate}} translates correctly. Therefore, in the getTranslation () specification, TranslateService retrieves data from Json files (en.json and de.json). I am mocking this service in TranslateServiceMock. How to check it? Any help?

+7
unit-testing angular karma-jasmine
source share
1 answer

You are testing a NavbarComponent, not a translation service. So, you want to check the contents of the navigation link, not the response from the service.

 import { By } from '@angular/platform-browser'; // ... // By.css: this example or some selection that gets the element you want const element = fixture.debugElement.query(By.css('.list-group-item > a')); // note: you should use ".toEqual('General')" if you want an exact match. expect(element.nativeElement.textContent).toContain('General'); 

But if you need to get a service instance handle:

 const translateService = fixture.debugElement.injector.get(TranslateService); 

You can find everything described here.

+1
source share

All Articles