首页 > 解决方案 > Angular 单元测试:访问模板变量

问题描述

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

标签: angularunit-testingjasminengx-bootstrap-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可以从您的组件访问模板变量。


推荐阅读