eba*_*nin 34 unit-testing angular2-template ng2-bootstrap angular
我正在写一个Angular 2单元测试.我有一个@ViewChild子组件,我需要在组件初始化后识别.在这种情况下,它是Timepickerng2-bootstrap库中的一个组件,但具体情况无关紧要.在我之后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)
}));
});
Run Code Online (Sandbox Code Playgroud)
伪代码按预期工作,直到您到达控制台日志.这timepickerChild是未定义的.为什么会这样?
yur*_*zui 20
我认为它应该有效.也许您忘记在配置中导入一些模块.以下是完整的测试代码:
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();
}));
});
Run Code Online (Sandbox Code Playgroud)
小智 5
在大多数情况下,只需将其添加到声明中即可。
beforeEach(async(() => {
TestBed
.configureTestingModule({
imports: [],
declarations: [TimepickerComponent],
providers: [],
})
.compileComponents()
Run Code Online (Sandbox Code Playgroud)