带TestBed的OverrideComponent [英] OverrideComponent with TestBed

查看:123
本文介绍了带TestBed的OverrideComponent的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有MainComponent使用ChildComponentA作为@ViewChild. MainComponent正在调用ChildComponentA上的方法.

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

我想编写一个模拟ChildComponentA的单元测试用例.如何使用TestBed(在Angular 2 RC5中)执行此操作?

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

在我以前使用overrideDirective(MainComponentName, ChildComponentA, MockChildComponentA);之前,是否使用TestBed等效于此?

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

我尝试使用

TestBed.overrideComponent(ChildComponentA,{
        set: {
          template: '<div></div>'
        }
      }); 

这只是设置模板,但我也想在组件中模拟方法.

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

推荐答案

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

I think in this case you can try and replace the child component with a mock component. Just create a mock component with the same selector and use TestBed to remove the declaration of the real child component and add the declaration to your mock component.

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

}

在您的测试中,请执行以下操作以使用模拟组件:

And in your test do this to use the mock component:

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

    TestBed.overrideModule(MyModule, {
        remove: {
            declarations: [ParentComponent, ChildComponent],
            exports: [ParentComponent, ChildComponent]
        }
    });

此处有更多详细信息: https://github.com/angular/angular/issues/10689 . 确保重新声明ParentComponent,否则它将无法正常工作(不确定原因).

More details here: https://github.com/angular/angular/issues/10689. Make sure to re-declare the ParentComponent, it does not work otherwise (not sure why).

如果使用@ViewChild来获取对子组件的引用,则需要对其进行修改,以不使用组件的类型,而是使用ID.使用@ViewChild('child')而不是@ViewChild(ChildComponent).从此处查看第二个示例: http://learnangular2.com/viewChild/

If you use @ViewChild to get a reference to the child component, you will need to modify it to not use the type of the component, but an id. Use @ViewChild('child') instead of @ViewChild(ChildComponent). See second example from here: http://learnangular2.com/viewChild/

这篇关于带TestBed的OverrideComponent的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆