微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

单元测试 – 角度2单元测试 – @ViewChild未定义

我正在写一个角度2单位测试.我有一个@ViewChild子组件,我需要在组件初始化后识别.在这种情况下,这是一个来自ng2-bootstrap库的Timepicker组件,虽然具体细节不重要.在检测到Changes()之后,子组件实例仍然未定义.

代码

@Component({
    template: `
        <form>
            <timepicker
                #timepickerChild
                [(ngModel)]="myDate">
            </timepicker>
        </form>
    `
})
export class ExampleComponent implements OnInit {
    @ViewChild('timepickerChild') timepickerChild: TimepickerComponent;
    public myDate = new Date();
}


// Spec
describe('Example Test',() => {
    let exampleComponent: ExampleComponent;
    let fixture: ComponentFixture<ExampleComponent>;

    beforeEach(() => {
        Testbed.configureTestingModel({
            // ... whatever needs to be configured
        });
        fixture = Testbed.createComponent(ExampleComponent);
    });

    it('should recognize a timepicker'. async(() => {
        fixture.detectChanges();
        const timepickerChild: Timepicker = fixture.componentInstance.timepickerChild;
        console.log('timepickerChild',timepickerChild)
    }));
});

代码按预期工作,直到您到达控制台日志. timepickerChild未定义.为什么会发生这种情况?

我认为它应该有效也许你忘了在配置中导入一些模块.以下是完整的测试代码
import { Testbed,ComponentFixture,async } from '@angular/core/testing';

import { Component,DebugElement } from '@angular/core';
import { FormsModule } from '@angular/forms';

import { ExampleComponent } from './test.component';
import { TimepickerModule,TimepickerComponent } from 'ng2-bootstrap/ng2-bootstrap';

describe('Example Test',() => {
  let exampleComponent: ExampleComponent;
  let fixture: ComponentFixture<ExampleComponent>;

  beforeEach(() => {
    Testbed.configureTestingModule({
      imports: [FormsModule,TimepickerModule.forRoot()],declarations: [
        ExampleComponent
      ]
    });
    fixture = Testbed.createComponent(ExampleComponent);
  });

  it('should recognize a timepicker',async(() => {
    fixture.detectChanges();
    const timepickerChild: TimepickerComponent = fixture.componentInstance.timepickerChild;
    console.log('timepickerChild',timepickerChild);
    expect(timepickerChild).tobedefined();
  }));
});

Plunker Example

原文地址:https://www.jb51.cc/angularjs/142782.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐