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

时间:2017-09-22 11:25:28

标签: angular jasmine karma-jasmine

FYI在github上记录了一个问题,并在bug中包含了plunkr,其中包含详细信息:https://github.com/angular/angular/issues/19292

我无法通过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');
  });

1 个答案:

答案 0 :(得分:14)

问题是,在您手动检测更改之前,DOM不会更新,并且您在->attach('photo', storage_path('app/public/testing/test_upload.jpg')); 呈现(并检测到*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'); }); 之前移动detectChanges()可以解决问题。