【问题标题】:Testing Template Reference Variable in Angular在 Angular 中测试模板引用变量
【发布时间】:2018-10-20 06:22:11
【问题描述】:

我有以下代码:

<input class="txt-port-id" id="portId"
     [value]="portIdFund1"
     maxlength="4"
     size="4"
     (keyup)="fundPortIdChanged(fund1PortId.value, 'fund1')"
     #fund1Port>

Angular 文档说passing-event-is-a-dubious-practice,因此传递了模板引用变量。我们如何在 Jasmine 中编写相同的单元测试?

【问题讨论】:

  • 你想要对上面的sn-p代码进行单元测试吗?
  • 是的,不确定方法是什么。尝试使用 triggerEventHandler 但没有工作

标签: angular jasmine angular-test


【解决方案1】:

您可以通过以下方式使用dispatchEvent

it('simple input test', fakeAsync(() => {
      const fundChangedSpy = spyOn(component, 'fundPortIdChanged').and.callThrough();
      const portIDInput: HTMLInputElement = fixture.debugElement.nativeElement.querySelector('#portId');
      expect(portIDInput.value).toEqual('');
      portIDInput.dispatchEvent(new Event('keyup'));
      fixture.detectChanges();
      tick(50);
      expect(portIDInput.value).toEqual('fund1');
      expect(fundChangedSpy).toHaveBeenCalledTimes(1);
}));

但据我了解,更鼓励在单元测试中使用 Reactive forms 而不是 Template-driven forms

响应式表单还提供了一种直接的测试途径,因为您可以确保您的数据在请求时是一致且可预测的。流的任何消费者都可以安全地操作该数据。

这是一个带有测试的stackblitz

【讨论】:

    猜你喜欢
    • 2018-07-14
    • 2017-04-27
    • 2017-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-12
    • 2020-08-23
    • 2019-02-01
    相关资源
    最近更新 更多