简体   繁体   English

在Angular中测试模板参考变量

[英]Testing Template Reference Variable in Angular

I have the following code: 我有以下代码:

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

Angular docs says passing-event-is-a-dubious-practice , thus passing template reference variable. Angular的文档说传递事件是一种可疑的做法 ,因此传递模板引用变量。 How do we write Unit Test in Jasmine for the same? 我们如何在Jasmine中编写单元测试呢?

What you can do is to use dispatchEvent in the following way: 您可以通过以下方式使用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);
}));

However as I understand it's more encouraged to use Reactive forms instead of Template-driven forms with unit testing. 但是,据我了解,在单元测试中,最好使用反应性表单而不是模板驱动的表单

Reactive forms also provide a straightforward path to testing because you are assured that your data is consistent and predictable when requested. 响应式表单还提供了一种直接的测试路径,因为可以确保在请求时确保数据的一致性和可预测性。 Any consumers of the streams have access to manipulate that data safely. 流的任何使用者都可以安全地操作该数据。

Here's a stackblitz with the test. 这是测试的重

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM