OverrideComponent with TestBed

Kas*_*yap 6 components overriding testbed angular

I have MainComponent that uses ChildComponentA as a @ViewChild. MainComponent is calling a method on ChildComponentA.

I want to write an unit test case mocking ChildComponentA. How can I do this using TestBed (in Angular 2 RC5)?

Before I used to use overrideDirective(MainComponentName, ChildComponentA, MockChildComponentA); Is there an equivalent to this using TestBed?

I tried using

TestBed.overrideComponent(ChildComponentA,{
        set: {
          template: '<div></div>'
        }
      }); 
Run Code Online (Sandbox Code Playgroud)

which just sets the template, but I want to mock the methods in the component as well.

小智 6

我认为在这种情况下,您可以尝试用模拟组件替换子组件。只需使用相同的选择器创建一个模拟组件,并使用 TestBed 删除真实子组件的声明并将声明添加到您的模拟组件中。

@Component({
  selector: 'child',
  template: '<div></div>'
})
class MockComponent {

}
Run Code Online (Sandbox Code Playgroud)

并在您的测试中执行此操作以使用模拟组件:

    TestBed.configureTestingModule({
        imports: [MyModule],
        declarations: [ParentComponent, MockComponent]
    });

    TestBed.overrideModule(MyModule, {
        remove: {
            declarations: [ParentComponent, ChildComponent],
            exports: [ParentComponent, ChildComponent]
        }
    });
Run Code Online (Sandbox Code Playgroud)

更多细节在这里:https : //github.com/angular/angular/issues/10689。确保重新声明 ParentComponent,否则它不起作用(不知道为什么)。

如果使用@ViewChild 来获取子组件的引用,则需要修改它以不使用组件的类型,而是使用 id。使用@ViewChild('child') 而不是@ViewChild(ChildComponent)。请参阅此处的第二个示例:http : //learnangular2.com/viewChild/