unit-testing - Angular 2 单元测试 - @ViewChild 未定义

标签 unit-testing angular angular2-template ng2-bootstrap

我正在编写 Angular 2 单元测试。我有一个 @ViewChild 子组件,我需要在组件初始化后识别它。在本例中,它是来自 ng2-bootstrap 库的 Timepicker 组件,但具体细节无关紧要。在我 detectChanges() 之后,子组件实例仍然未定义。

伪代码:

@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

关于unit-testing - Angular 2 单元测试 - @ViewChild 未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42724179/

相关文章:

unit-testing - 试图获得对 TDD 好处的信心

Angular 测试在初始化前无法访问服务

html - 如何设置 Angular Material select 下拉叠加层的样式

angular - 在 Angular 中的项目之间共享服务的最佳实践

angular - 如何预加载 angular2 View 以便在第一次加载时不会闪烁白页?

Angular 2 错误 : Can't bind to 'innerhtml' since it isn't a known native property

typescript - 使用 FormBuilder Angular 2 绑定(bind)选择列表

javascript - 模块功能上的 sinon stub

unit-testing - 如何在带有 Jest 的 react-native 中使用模拟的 fetch() 对 API 调用进行单元测试

javascript - Angular 4 中动态嵌套路由器导出的使用