Bypass * ngIf on Angular / Jasmine unit test

FYI Forgot the github question, and also included plunkr in the error with details: https://github.com/angular/angular/issues/19292

I just can't pass ngIf to check the value. If I remove ngIf, it will work fine. To try to get around this, I hard-coded the ambassador value directly in beforeEach (). But I have nothing to lose.

In HTML:

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

Jasmine:

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');
  });
+4
source share
1 answer

The problem is that the DOM is not updated until you detect the changes manually and you try to query the DOM before the value *ngIf(s ambassador) is shown .

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

detectChanges() query() .

+5

Source: https://habr.com/ru/post/1686202/


All Articles