如何将 DOM 元素附加到 angular 2 TestBed?

How to append a DOM element to an angular 2 TestBed?

切入正题,我想知道是否有办法在测试 DOM 前添加一个 DOM 元素。我是测试新手,但有点像 fixture.degugElement.prepend('div')。根据我对测试的了解,这可能揭示了一个设计缺陷,所以如果你想要一些理由,我已经在下面添加了原因。

为什么我需要这样做:

在我的应用程序中,我有一个类似于 this 以前版本的文本代码指令。为了发挥作用,我必须测量文本的长度。为此,我创建了一个幽灵元素并将其粘贴到我的 AppComponent

@Component({
  selector: 'app-root',
  template: `
    <div id="ghost"></div> <!-- THIS IS THE GUY I NEED -->
    <div class="main-area">
      <router-outlet></router-outlet>
    </div>
  `,
  styleUrls: ['./app.component.scss']
})

不幸的是,我需要这个元素在原处,因为 css 定位需要正确测量它,但这意味着它在我的测试中不可用。

看起来像这样:

const newTemplate = `<div id="ghost"></div>${oldTemplate}`

...

beforeEach(async(() => {
  TestBed.configureTestingModule({
    declarations: [ComponentUnderTest],
    // ... more module stuff
  }).overrideTemplate(ComponentUnderTest, newTemplate )
  .compilecomponents();
}));