我有一个父组件:
@Component({
selector: 'parent-component',
directives: [I18nDirective, child-component],
template: require('./parent.component.html'),
styles: [require('./parent.component.scss')],
})
export class ParentComponent {
}
然后我有子组件:
@Component({
selector: 'child-component',
template: require('./child-component.component.html'),
styles: [require('./child-component.component.scss')]
})
export class ChildComponent {
constructor(private _eventAggregator: EventAggregatorService, private _zone: NgZone) {}
在父组件的html中,我使用:child-component
问题在于子组件的规范测试。他们在考试时通过:
describe('Center On Me Button', () => {
let fixture;
let nativeElement;
let componentInstance;
beforeEachProviders(() => [
ChildComponent,
EventAggregatorService,
GeoLocationService,
provide(GoogleMapsAPIWrapper, {useClass: StabGoogleMapsApiWrapper}),
provide(MapController, {useClass: StabMapControllerService}),
provide(MapEventsService, {useClass: StabMapEventsService})
]);
beforeEach(injectAsync([TestComponentBuilder, GoogleMapsAPIWrapper, GeoLocationService, MapController, EventAggregatorService
], (tcb: TestComponentBuilder ) => {
return tcb
.createAsync(ChildComponent).then((componentFixture: ComponentFixture<ChildComponent>) => {
({nativeElement, componentInstance} = componentFixture);
fixture = componentFixture;
componentFixture.detectChanges();
});
it('should enable Geolocation button when it is clicked', done => {
componentInstance.isGeoLocationButtonEnabled = false;
nativeElement.querySelector('.toggle.fa.fa-crosshairs').click();
expect(componentInstance.isGeoLocationButtonEnabled).toBe(true);
done();
});
}));
我的问题是在这样的配置中测试通过了。但是,只要我想将服务实例添加到子组件构造函数中,测试就不会通过(在parent.component.spec中失败),并显示以下消息:
TypeError: undefined is not an object (evaluating 'fixture.detectChanges') ... in parent.component.spec.ts
我所做的就是添加: private someService:SomeService到子组件的构造函数。所以我现在有:
export class ChildComponent {
constructor(private _eventAggregator: EventAggregatorService, private _zone: NgZone, private _someService: SomeService) {}
我添加的这项服务被添加到角度应用程序顶层的提供者列表中。当然,我将它添加到测试本身的提供者列表中。
当我这样做时,测试开始失败,我写的上一条消息。为什么这样呢?我真的不明白这种行为,资源在网络中受到限制。还没有文档。