Angular 测试:覆盖以使用模板而不是 templateUrl

Mar*_*Nuc 3 testing mocking testbed angular

我有一个包含iframe. 为了防止在测试中从 iframe 加载不存在的 URL,我想模拟组件的模板。我以为我可以用TestBed.overrideComponent()它来做,但它没有效果。当测试运行时,我可以看到原始模板存在并且 iframe 加载不存在的 url。

我试过的:

fixture = TestBed.overrideComponent(IFrameComponent, {
  remove: {
    templateUrl: './iframe.component.html'
  },
  add: {
    template: '<div></div>'
  }
}).createComponent(IFrameComponent);
Run Code Online (Sandbox Code Playgroud)

如何覆盖要使用的组件template而不是templateUrl

Mar*_*Nuc 6

它对我不起作用的原因是我TestBed.overrideComponent() compileComponents().

正确的顺序是这样的:

TestBed.configureTestingModule({
   declarations: [IFrameComponent]
}).overrideComponent(IFrameComponent, {
   remove: {
      templateUrl: './iframe.component.html'
   },
   add: {
      template: '<div data-test-iframe="iframe"></div>'
   }
}).compileComponents();
fixture = TestBed.createComponent(IFrameComponent);
Run Code Online (Sandbox Code Playgroud)