在Angular/Jasmine单元测试中绕过*ngIf

Jor*_*ald 7 jasmine karma-jasmine angular

仅供参考我在github上记录了一个问题,并在bug中包含了plunkr的详细信息:https://github.com/angular/angular/issues/19292

我根本无法通过ngIf来检查值.如果我删除ngIf它工作正常.为了试图解决这个问题,我直接在beforeEach()中硬编了大使的价值.但无济于事我错过了别的东西.

在HTML中:

 <h3 class="welcome" *ngIf="ambassador"><i>{{ambassador.username}}</i></h3>
Run Code Online (Sandbox Code Playgroud)

茉莉花:

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');
  });
Run Code Online (Sandbox Code Playgroud)

Z. *_*ley 14

问题是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');
  });
Run Code Online (Sandbox Code Playgroud)

移动detectChanges()之前query()应该解决问题.