2016-12-30 7 views
9

मैं एक Angular2 परीक्षण घटक लिख रहा हूँ से तत्व प्राप्त करें और मैं ट्यूटोरियल में इस लाइन ध्यान दिया है:Angular2 परीक्षण - ईद

de = fixture.debugElement.query(By.css('h1')); 

deDebugElement प्रकार के रूप में परिभाषित किया गया है।

मैं आईडी द्वारा DebugElement कैसे प्राप्त कर सकता हूं?

यह बहुत आसान प्रतीत हो सकता है लेकिन मुझे दस्तावेज़ों में कोई दिशा नहीं मिल रही है।

उत्तर

11

तुम भी मेरे लिए by.css

de = fixture.debugElement.query(by.css('#theid')); 
+0

मुझे मिल रहा है: TypeError: platform_browser_ 1.By.id एक फंक्शन नहीं है – ohadinho

+1

मुझे लगता है कि आपका उदाहरण कोणीय 1 दस्तावेज़ – ohadinho

+0

से संबंधित है क्या आपने by.css चयनकर्ता आईडी के लिए हैश का उपयोग करने का प्रयास किया है? –

-1

काम का उपयोग कर सकते हैं:

फ़ाइल ... component.html:

<ul id="submenu"> 

    <li> 
     <a [routerLink]="['blankpage']"><span>Blank Page</span></a> 
    </li> 
</ul> 

फ़ाइल ...- spec.ts:

import { SidebarComponent} from './sidebar'; 
import { TestBed, async } from '@angular/core/testing'; 
import { HttpModule } from '@angular/http'; 
import { RouterTestingModule } from '@angular/router/testing'; 
import { ComponentFixture} from '@angular/core/testing'; 
import { By }    from '@angular/platform-browser'; 
import { DebugElement } from '@angular/core'; 

describe('...',() => { 
let comp : SidebarComponent; 
let fixture : ComponentFixture<SidebarComponent>; 
let de : DebugElement; 
beforeEach(async(() => { 
    TestBed.configureTestingModule({ 
     declarations: [ 
     SidebarComponent 
     ], 
     imports: [RouterTestingModule,HttpModule] 
    }).compileComponents(); 
    })); 
    beforeEach(() => { 
    TestBed.configureTestingModule({ 
     declarations: [ 
      SidebarComponent 
     ] 
    }); 
    TestBed.compileComponents(); 
    fixture = TestBed.createComponent(SidebarComponent); 
    fixture.detectChanges(); 
    de = fixture.debugElement; 
}); 

it('Sidebar element "Blank Page" was created',() => { 
     expect(de.nativeElement.querySelector('ul.submenu a span').textContent).toContain('Blank Page') 
     expect(de.nativeElement.querySelector('ul.submenu a span').textContent).toBeDefined() 
    }); 

    it('Checking ul id',() => { 
    expect(de.nativeElement.querySelector('ul').getAttribute('id')).toMatch('submenu') 
    }); 

)} 
+0

यह आईडी के बारे में सवाल को पूरी तरह से अनदेखा करता है। –

+0

लॉल ... सीएसएस में चयनकर्ताओं को 'आईडी' और 'कक्षा' के बीच क्या अंतर है? –

+0

मुद्दा यह है कि ओपी के पास अपने तत्वों पर संभवतः 'आईडी' है और वह अपने परीक्षणों में उन्हें ढूंढने के लिए इसका उपयोग करना चाहता है, और आपके हालिया संपादन तक आपकी प्रतिक्रिया में 'आईडी' का कोई उल्लेख नहीं था। फिर भी, यह जेजेबी के अच्छे और संक्षिप्त उत्तर से थोड़ा कम मूल्य प्रदान करता है। 'By.css (" # myid ") 'बेहतर तरीका है। –