加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

unit-testing – 从Angular 2测试中更新输入html字段

发布时间:2020-12-17 07:54:39 所属栏目:安全 来源:网络整理
导读:我想在Angular 2单元测试中更改输入字段的值. input type="text" class="form-control" [(ngModel)]="abc.value" / 我不能只更改ngModel,因为abc对象是私有的: private abc: Abc = new Abc(); 在Angular 2测试中,我可以模拟用户在输入字段中输入的内容,以便
我想在Angular 2单元测试中更改输入字段的值.
<input type="text" class="form-control" [(ngModel)]="abc.value" />

我不能只更改ngModel,因为abc对象是私有的:

private abc: Abc = new Abc();

在Angular 2测试中,我可以模拟用户在输入字段中输入的内容,以便使用用户在单元测试中输入的内容更新ngModel吗?

我可以毫无问题地获取输入字段的DebugElement和nativeElement. (只是在输入字段的nativeElement上设置value属性似乎不起作用,因为它不会使用我为该值设置的内容更新ngModel).

也许可以调用inputDebugEl.triggerEventHandler,但是我不确定给它的参数是什么,因此它将模拟输入特定字符串的用户.

你是对的,你不能只设置输入,你还需要调度’输入’事件.这是我今天早些时候写的一个函数来输入文本:
function sendInput(text: string) {
  inputElement.value = text;
  inputElement.dispatchEvent(new Event('input'));
  fixture.detectChanges();
  return fixture.whenStable();
}

这里fixture是ComponentFixture,inputElement是fixture的nativeElement的相关HTTPInputElement.这会返回一个promise,所以你可能需要解析它sendInput(‘whatever’).然后(…).

在上下文中:https://github.com/textbook/known-for-web/blob/52c8aec4c2699c2f146a33c07786e1e32891c8b6/src/app/actor/actor.component.spec.ts#L134

更新:

我们在Angular 2.1中遇到了一些问题,它不喜欢创建一个新的事件(…),所以我们做了:

import { dispatchEvent } from '@angular/platform-browser/testing/browser-util';

...

function sendInput(text: string) {
  inputElement.value = text;
  dispatchEvent(fixture.nativeElement,'input');
  fixture.detectChanges();
  return fixture.whenStable();
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读