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

Angular Unit Test: Access template variable

我在组件模板中有这段代码,它打开了一个 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 模板调用的变量作为参数。我怎样才能做到这一点?

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

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

@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演示。