测试在调试元素之外注入的 Angular 对话框 window

Testing an Angular dialog window which is injected outside of debug element

我正在使用 Angular material dialog window

在我的测试中,我触发了模态 window。但它将模态 window 放在调试元素之外。在浏览器中它看起来像这样:

带有id="root1"的div是调试元素。 div 和 class cdk-overlay-container 是我想要断言的模式。

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

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

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

尝试使用 document 对象本身。

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

发现 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 的内部内容和 class 'cdk-overlay-container'.

还不确定如何使用 getContainerElement..