2

我在组件模板中有这段代码,它打开了一个 ngx-bootstrap 模式:

<button type="button"
        class="btn btn-primary"
        (click)="onOpenSharesModal(modal)">Click me!</button>
<ng-template #modal>
    <app-modal (closed)="onCloseSharesModal()"></app-modal>
</ng-template>

零件:

onOpenSharesModal(template: TemplateRef<any>) {
    this.modalRef = this.modalService.show(template, { class: 'modal-lg' });
}

测试:

it('should call onOpenSharesModal() when button clicked', () => {
  const button = fixture.debugElement.query(By.css('button'));
  const spy = spyOn(component, 'onOpenSharesModal');

  button.triggerEventHandler('click', null);
  fixture.detectChanges();

  expect(spy).toHaveBeenCalled();
});

我正在尝试测试组件:我已经能够测试onOpenSharesModal()正在调用的组件,但我想测试它是否以modal模板变量作为参数调用。我怎样才能做到这一点?

4

2 回答 2

2

您可以使用间谍来监视函数并检查作为参数传递的内容。假设您的组件被调用MyComponent。在你的单元测试文件中你有(有点缩短,但你应该得到图片):

let myComponent: MyComponent = fixture.componentInstance;

// Set up a spy on your function
let spy = spyOn(myComponent, 'onOpenSharesModal').and.callThrough();

// After the function has been called somewhere in your component
expect(spy).toHaveBeenCalled();

// Check the arguments that were passed
expect(spy.calls.mostRecent().args[0]).toEqual(myComponent.modal);

这是假设modal可以从您的组件访问模板变量。

于 2019-01-08T11:11:42.677 回答
1

首先,您需要将以下行添加到组件中,以便可以引用模态模板变量:

@ViewChild('modal') myModal: TemplateRef<any>; // for testing

现在您可以在测试中引用组件变量“myModal”:

it('should call onOpenSharesModal() when button clicked', () => {
  const button = fixture.debugElement.query(By.css('button'));
  const spy = spyOn(component, 'onOpenSharesModal');

  button.triggerEventHandler('click', null);
  fixture.detectChanges();

  expect(spy).toHaveBeenCalled();
  expect(spy).toHaveBeenCalledWith(component.myModal);
});

这是一个有效的StackBlitz来演示。

于 2019-01-08T19:17:22.413 回答