2017-09-22 32 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()应该解决的问题。