在console.log上,未在单元测试中定义ViewChild变量 [英] On console.log, ViewChild variable is undefined in unit test

查看:74
本文介绍了在console.log上,未在单元测试中定义ViewChild变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试测试具有@ViewChild批注的组件.我要测试的功能之一就是调用@ViewChild的元素来获得焦点.但是,当我尝试注销@ViewChild变量时,它始终是undefined.我以为componentFixture.detectChanges()会启动ElementRef,但似乎没有.

I'm trying to test a component that has an @ViewChild annotation. One of the functions that I'm trying to test calls the @ViewChild's element for focus. However, when I try to log out the @ViewChild variable, it is always undefined. I thought componentFixture.detectChanges() would initiate the ElementRef, but it doesn't seem to.

有没有办法做到,所以不是undefined?

Is there any way to make it so it isn't undefined?

推荐答案

我不知道您使用的是哪个Angular2版本以及如何初始化测试套件,但是ComponentFixture实例上的detectChanges方法负责设置此类字段.

I don't know which version of Angular2 you use and how you initialize your test suite but the detectChanges method on the ComponentFixture instance is responsible to set such fields.

以下是显示此内容的示例测试:

Here is a sample test that shows this:

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');
    });
}));

请参见相应的插件: https://plnkr.co/edit/THMBXX?p=preview .

这篇关于在console.log上,未在单元测试中定义ViewChild变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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