代码之家  ›  专栏  ›  技术社区  ›  Martin Nuc

角度测试:重写以使用模板而不是模板URL

  •  2
  • Martin Nuc  · 技术社区  · 7 年前

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

    我尝试过:

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

    如何重写要使用的组件 template 而不是 templateUrl ?

    1 回复  |  直到 7 年前
        1
  •  1
  •   Martin Nuc    7 年前

    它对我不起作用的原因是我打过电话 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);