从子组件到父组件的输出事件绑定

时间:2020-03-18 07:39:29

标签: angular jasmine

我正在组件代码中为方法ngAfterViewInit编写单元测试。我正在使用Jasmine karma作为测试工具。目前,代码覆盖范围抱怨说 不会覆盖this.closeModal()(称为订阅的一部分)。

基本上,我正在将子组件引用传递给父组件。如您所见,子组件具有名为closeModal的输出事件。父组件正在订阅它。正如您在下面的代码中看到的那样,我在测试中做了以下操作。那就是将closeModal输出事件绑定到父组件,并尝试通过子组件发出事件。这似乎也不起作用。我绑定的方式有问题吗?

 component.ngAfterViewInit();
    component.closeModal.bind(childComponent.closeModal);
    component.componentRef.instance.closeModal.subscribe(() => {
      tick();
       childComponent.closeModal.emit(true);
      expect(component.closeModal).toHaveBeenCalled();

父项

export class ModalDialogComponent implements AfterViewInit, OnDestroy {
  private readonly _onClose = new Subject<any>();

  public componentRef: ComponentRef<any>;
  public childComponentType: Type<any>;
  public onClose = this._onClose.asObservable();

  // add this:
  @ViewChild(InsertionDirective, { static: false })
  insertionPoint: InsertionDirective;

  constructor(public componentFactoryResolver: ComponentFactoryResolver,
              public cd: ChangeDetectorRef,
              public dialog: ModalDialogRef) {
  }

  ngAfterViewInit() {
    this.loadChildComponent(this.childComponentType);
    this.cd.detectChanges();
  }

  loadChildComponent(componentType: Type<any>) {
    const componentFactory = this.componentFactoryResolver.resolveComponentFactory(componentType);
    const viewContainerRef = this.insertionPoint.viewContainerRef;
    viewContainerRef.clear();
    this.componentRef = viewContainerRef.createComponent(componentFactory);
    this.componentRef.instance.closeModal.subscribe(() => this.closeModal());
  }

  closeModal() {
    this.dialog.close();
  }
}

子组件

@Component({
  selector: 'app-example',
  templateUrl: './example.component.html'
})

export class ExampleComponent {
  @Output() closeModal = new EventEmitter<boolean>();
  constructor(public config: ModalDialogConfig,
              public dialog: ModalDialogRef
              ) {}

  onCancel() {
    this.dialog.close('user clicked cancel');
  }

  onOk() {
    this.dialog.close('User clicked ok');
  }
}

测试

fdescribe('ModalDialogComponent', () => {
  let component: ModalDialogComponent;
  let childComponent: ExampleComponent;
  let fixture: ComponentFixture<ModalDialogComponent>;
  let childFixture: ComponentFixture<ExampleComponent>;
  let mockMouseEvent;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [SharedModule, ModalDialogModule, NgxsModule.forRoot([])],
      providers: [ModalDialogConfig, ModalDialogRef ]
    })
    .overrideModule(BrowserDynamicTestingModule, { set: { entryComponents: [ModalDialogComponent, ExampleComponent] } })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(ModalDialogComponent);
    childFixture = TestBed.createComponent(ExampleComponent);
    mockMouseEvent = new Mock<MouseEvent>({ stopPropagation: () => Promise.resolve(true) });
    component = fixture.componentInstance;
    childComponent = childFixture.componentInstance;

    component.childComponentType = ExampleComponent;

    component.componentRef = childFixture.componentRef;
    spyOn(component.componentRef.instance, 'closeModal').and.returnValue(Observable.of(true));
    fixture.detectChanges();
  });

  it('should call ngAfterViewInit ', () => {

    component.ngAfterViewInit();
    component.closeModal.bind(childComponent.closeModal);
    component.componentRef.instance.closeModal.subscribe(() => {
      tick();
        childComponent.closeModal.emit(true);
      expect(component.closeModal).toHaveBeenCalled();

    });

  });

1 个答案:

答案 0 :(得分:0)

问题已解决。我只需要添加这一行代码 component.componentRef.instance.closeModal.emit(true);