2017-09-22 36 views
4

FYI登錄GitHub上的問題,也包括plunkr與細節錯誤:https://github.com/angular/angular/issues/19292旁路* ngIf上的角/茉莉花單元測試

我根本無法獲得,以檢查值傳遞ngIf。如果我刪除ngIf它可以正常工作。爲了嘗試解決這個問題,我直接在beforeEach()中硬編碼了大使的價值。但無濟於事我錯過了別的東西。

在HTML:

<h3 class="welcome" *ngIf="ambassador"><i>{{ambassador.username}}</i></h3> 

茉莉花:

beforeEach(() => { 

    TestBed.configureTestingModule({ 
     declarations: [ ProfileComponent, BannedComponent ], 
     providers: [ HttpClient, {provide: AmbassadorService, useClass: MockAmbassadorService } ], 
     imports:  [ RouterTestingModule, FormsModule, HttpClientModule ] 
    }); 

    fixture = TestBed.createComponent(ProfileComponent); 
    component = fixture.componentInstance; 

    // AmbassadorService actually injected into the component 
    ambassadorService = fixture.debugElement.injector.get(AmbassadorService); 
    componentUserService = ambassadorService; 
    // AmbassadorService from the root injector 
    ambassadorService = TestBed.get(AmbassadorService); 

    // set route params 
    component.route.params = Observable.of({ username: 'jrmcdona' }); 
    component.ambassador = new Ambassador('41', '41a', 'jrmcdona', 4586235, false); 
    component.ngOnInit(); 
    }); 

    it('should search for an ambassador based off route param OnInit',() => { 
    de = fixture.debugElement.query(By.css('.welcome')); 
    el = de.nativeElement; 
    fixture.detectChanges(); 
    const content = el.textContent; 
    expect(content).toContain('jrmcdona', 'expected name'); 
    }); 
+0

正如您在列出的問題中提到的,您也可以使用'fixture.autoDetectChanges()'自動檢測更改,但顯式檢測更加可靠。 – estus

回答

5

的問題是,DOM不更新,直到手動發現變化,而你試圖您*ngIf前查詢DOM呈現(並檢測到ambassador值)。

it('should search for an ambassador based off route param OnInit',() => { 
    fixture.detectChanges(); 
    de = fixture.debugElement.query(By.css('.welcome')); 
    el = de.nativeElement; 
    const content = el.textContent; 
    expect(content).toContain('jrmcdona', 'expected name'); 
    }); 

移動query()以前detectChanges()應該解決的問題。