Unit testing 在console.log上,ViewChild变量在单元测试中未定义
我正在尝试测试具有Unit testing 在console.log上,ViewChild变量在单元测试中未定义,unit-testing,angular,karma-jasmine,Unit Testing,Angular,Karma Jasmine,我正在尝试测试具有@ViewChild注释的组件。我尝试测试的函数之一调用了@ViewChild的元素作为焦点。但是,当我尝试注销@ViewChild变量时,它总是未定义的。我以为componentFixture.detectChanges()会启动ElementRef,但它似乎没有 有没有办法使它不被定义?我不知道您使用的是哪个版本的Angular2以及如何初始化您的测试套件,但是ComponentFixture实例上的detectChanges方法负责设置这些字段 下面是一个示例测试,它显示
@ViewChild
注释的组件。我尝试测试的函数之一调用了@ViewChild
的元素作为焦点。但是,当我尝试注销@ViewChild
变量时,它总是未定义的
。我以为componentFixture.detectChanges()
会启动ElementRef
,但它似乎没有
有没有办法使它不被定义?我不知道您使用的是哪个版本的Angular2以及如何初始化您的测试套件,但是
ComponentFixture
实例上的detectChanges
方法负责设置这些字段
下面是一个示例测试,它显示了这一点:
it('should set testElt', injectAsync([TestComponentBuilder], (tcb: TestComponentBuilder) => {
return tcb.createAsync(MyList).then((componentFixture: ComponentFixture) => {
expect(componentFixture.componentInstance.testElt).toBeUndefined();
componentFixture.detectChanges();
expect(componentFixture.componentInstance.testElt).toBeDefined();
var testElt = componentFixture.componentInstance.testElt;
expect(testElt.nativeElement.textContent).toEqual('Some test');
});
}));
查看相应的plunkr:。您没有显示代码,但是,可能您没有定义代码,因为您执行了ViewChild,如:
@ViewChild(MySubComponent)
而不是
@ViewChild('componentref')
然后在模板中:
<my-sub-component #componentref></my-sub-component>
当然,您需要使用
componentFixture.detectChanges()
初始化组件,您是否介意显示一些代码来演示您试图完成的任务?以及如何在测试中引用模拟组件本身?尝试使用testBed.get(ChildComponentName),查看测试床api,我看不到任何其他本机方式。它确实适用于服务:)不推荐的另一种方法是将@ViewChild公开给测试组件的公共属性。但总的来说,我喜欢把组件当作一个普通类来对待。在这种情况下,您创建模拟组件只是为了满足测试组件的创建,然后忘记它们。