角单元测试:访问模板变量

时间:2019-01-08 09:45:45

标签: angular unit-testing jasmine ngx-bootstrap-modal

我在组件模板中有此代码,该模板打开了ngx-bootstrap模态:

Xyz_controller.php

组件:

<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()模板变量来调用它,例如论点。我怎样才能做到这一点?

2 个答案:

答案 0 :(得分:1)

您可以使用间谍来监视该函数,并检查作为参数传递的内容。假设您的组件名为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模板变量。

答案 1 :(得分: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正在演示的工作。