2016-12-16 13 views
7

में कर्म-चमेली का उपयोग कर रहा जर्मन और अंग्रेजी विकल्प का उपयोग NG2-अनुवाद के साथ पृष्ठ का अनुवाद करने की कोशिश कर रहा हूँ NG2-अनुवाद करते हैं।कैसे करें इकाई परीक्षण Angular2

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


    }) 
}); 

अनुवाद हो रहा है और {{ 'PAGE.GENERAL' | अनुवाद}} ​​ का अनुवाद ठीक से हो रहा है। तो spec में, अनुवाद सेवा का getTranslation() जेसन फाइलों से डेटा ला रहा है (en.json & de.json)। मैं TranslateServiceMock में इस सेवा का मज़ाक उड़ा रहा हूं। मैं इसका परीक्षण कैसे करूं? कोई मदद?

उत्तर

1

आप NavbarComponent का परीक्षण कर रहे हैं, अनुवाद सेवा नहीं। तो आप जो चाहते हैं वह है Navbar लिंक की सामग्री की जांच करना, सेवा से प्रतिक्रिया नहीं।

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

लेकिन, यदि आप सेवा उदाहरण पर एक संभाल पाने के लिए की जरूरत है:

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

आप this documented here.

के सभी पा सकते हैं
संबंधित मुद्दे