【问题标题】:Testing an Angular dialog window which is injected outside of debug element测试在调试元素之外注入的 Angular 对话框窗口
【发布时间】:2020-12-10 19:09:09
【问题描述】:

我正在使用Angular material dialog window

在我的测试中,我触发了模态窗口。但它将模式窗口放在调试元素之外。在浏览器中是这样的:

带有id="root1" 的div 是调试元素。 cdk-overlay-container 类的 div 是我要断言的模态。

如果它在调试元素之外,我该怎么做?

例如,我想将模式作为调试元素。然后测试是否显示正确的标题:

let modal = ??;
expect(modal.query(By.css('h1')).nativeElement.innerText).toBe('My Title')`;

【问题讨论】:

    标签: angular angular-material jasmine


    【解决方案1】:

    尝试使用 document 对象本身。

    let modal = document.querySelector('.cdk-overlay-container');
    let title = modal.querySelector('h1');
    expect(title.innerText).toContain('My Title');
    

    【讨论】:

    • 我喜欢这给你原始的 DOM 元素。根据您的经验,使用文档是否比使用自定义耐火材料更好?我想知道为什么我回答中的文章作者会遇到使用工厂的麻烦。
    • 有趣。尝试按照文章的方式进行。我这样说是因为要使文档正常工作,您必须在浏览器中进行单元测试。一些项目可能会使用 jest 或其他使用 jsdomdocument.querySelector(..) 的测试框架将返回 undefined 因为浏览器 dom 中将没有任何内容(没有浏览器,测试正在终端中运行)。
    • 好一个。那么使用 DOM 可能实际上是一个好主意,因为这将更接近地模仿用户的环境。 Jest 确实使用了 jsdom,并且 document.querySelector 会返回一些东西:jestjs.io/docs/en/configuration
    【解决方案2】:

    找到this article 解释你可以添加一个带有工厂的提供者来获取overlayContainer:

    import { OverlayContainer } from '@angular/cdk/overlay';
    
    //... 
    
      let overlayContainerElement: HTMLElement;
    
      await TestBed.configureTestingModule({
        // ...
        providers: [
          {
            provide: OverlayContainer,
            useFactory: () => {
              overlayContainerElement = document.createElement('div');
              return { getContainerElement: () => overlayContainerElement };
            }
          }
       ]
    // ...
    

    现在,当我使用 overlayContainerElement 时,我会得到一个 div,其中包含原始 div 的内部内容以及类“cdk-overlay-container”。

    还不确定如何使用getContainerElement..

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-05
      相关资源
      最近更新 更多