【问题标题】:iframe content not loaded while testing in Angular / Karma在 Angular / Karma 中测试时未加载 iframe 内容
【发布时间】:2021-03-29 05:55:02
【问题描述】:

我在另一个名为 mainApp 的应用程序中使用 .我想对集成导航模块的 mainApp 的 HomeComponent 进行单元测试,如下代码所示

 <iframe class="ext-navigation" src="http://localhost:4200/" title="navigation" loading="eager"></iframe>

在浏览器上一切正常,导航显示没有任何问题,但是在测试时我无法在测试日志中获取导航的内容,它显示 iframe 的内容为空

这是我的测试代码:

  it('should contain the navigation links', async() => {
    fixture.detectChanges();  
    await fixture.whenStable();
    fixture.whenStable().then(()=>{
       fixture.detectChanges();  
       console.log(fixture.debugElement.nativeElement.querySelector('.ext-navigation '));
    })
    const compiled = fixture.debugElement.nativeElement;
    console.log(compiled.querySelector('.ext-navigation body'));
 
   expect(compiled.querySelector('app-navigation').textContent).toContain('home');
 });

有谁知道如何等待 iframe 内容加载才能在 spec.ts 中对其进行测试?

【问题讨论】:

    标签: angular unit-testing iframe jasmine karma-jasmine


    【解决方案1】:

    最后,我成功地解决了这个问题

     <iframe class="ext-navigation" [src]="url" title="navigation" loading="eager" (load)="iframeSrc && iframeLoaded()"></iframe>
    

    并在组件ts文件中添加了这个Subject等待加载内容

    public iframesLoaded: Subject<void> = new Subject();
    
    public iframeLoaded(index: number) {
        this.iframesLoaded.next();
      }
    

    对于我的测试用例,我将 iframeSrc 值设置为真实值,并订阅了 Subject 以获得最终值:

      it('should display the navigation menu ["Home", "Contact", "About"]', (done) => {
        let fixture = TestBed.createComponent(NavbarComponent);
        let component = fixture.componentInstance;
        component.iframeSrc = '/iframe';
        fixture.detectChanges();
        component.iframesLoaded.pipe(take(1)).subscribe(val => {
          fixture.detectChanges();
    
          let navLinks = Array.from(fixture.nativeElement.querySelector('.ext-navigation').contentDocument.querySelectorAll('body ul a')).map((item: Node) => item.textContent)
          expect(navLinks).toContain("Home")
          expect(navLinks).toContain("Contact")
          expect(navLinks).toContain("About")
    
          done();
        });
      });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-11-07
      • 1970-01-01
      • 1970-01-01
      • 2016-12-18
      • 2014-02-07
      • 2016-11-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多