Angularjs   发布时间:2022-04-20  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了单元测试 – 角度2单元测试 – @ViewChild未定义大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在写一个角度2单位测试.@L_675_1@一个@ViewChild子组件,我需要在组件初始化后识别.在这种情况下,这是一个来自ng2-bootstrap库的Timepicker组件,然具体细节不重要.在检测到Changes()之后,子组件实例仍然未定义.

代码:@H_696_2@

@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.con@L_772_6@ureTesTingModel({
            // ... whatever needs to be con@L_772_6@ured
        });
        fixture = TESTBed.createComponent(ExampleComponent);
    });

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

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

我认为它应该有效也许你忘了在配置中导入一些模块.以下是完整的测试代码
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.con@L_772_6@ureTesTingModule({
      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@H_696_2@

大佬总结

以上是大佬教程为你收集整理的单元测试 – 角度2单元测试 – @ViewChild未定义全部内容,希望文章能够帮你解决单元测试 – 角度2单元测试 – @ViewChild未定义所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。