【问题标题】:Bypassing *ngIf on an Angular/Jasmine unit test在 Angular/Jasmine 单元测试中绕过 *ngIf
【发布时间】:2017-09-22 11:25:28
【问题描述】:

仅供参考 在 github 上记录了一个问题,并将 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');
  });

【问题讨论】:

  • 正如您列出的问题中提到的那样,您也可以使用fixture.autoDetectChanges() 自动检测更改,尽管显式检测更可靠。

标签: angular jasmine karma-jasmine


【解决方案1】:

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

detectChanges() 移到query() 之前应该可以解决问题。

【讨论】:

    猜你喜欢
    • 2017-04-04
    • 1970-01-01
    • 2020-11-12
    • 2018-09-10
    • 2017-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多