从 Angular 2 测试中更新输入 html 字段 [英] Updating input html field from within an Angular 2 test

查看:21
本文介绍了从 Angular 2 测试中更新输入 html 字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 Angular 2 单元测试中更改输入字段的值.

I would like to change the value of an input field from within an Angular 2 unit test.

<input type="text" class="form-control" [(ngModel)]="abc.value" />

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

I can't just change the ngModel because abc object is private:

 private abc: Abc = new Abc();

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

In Angular 2 testing, can I simulate the user typing into the input field so that the ngModel will be updated with what the user has typed from within a unit test?

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

I can grab the DebugElement and the nativeElement of the input field without a problem. (Just setting a the value property on the nativeElement of the input field doesn't seem to work as it doesn't update the ngModel with what I've set for the value).

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

Maybe inputDebugEl.triggerEventHandler can be called, but I'm not sure what arguments to give it so it will simulate the user having typed a particular string of input.

推荐答案

你说得对,你不能只设置输入,你还需要调度 'input' 事件.这是我今晚早些时候编写的用于输入文本的函数:

You're right that you can't just set the input, you also need to dispatch the 'input' event. Here is a function I wrote earlier this evening to input text:

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

这里fixtureComponentFixtureinputElement是来自fixture的nativeElement<的相关HTTPInputElement/代码>.这将返回一个承诺,因此您可能必须解决它sendInput('whatever').then(...).

Here fixture is the ComponentFixture and inputElement is the relevant HTTPInputElement from the fixture's nativeElement. This returns a promise, so you'll probably have to resolve it sendInput('whatever').then(...).

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

更新:

我们在 Angular 2.1 中使用它时遇到了一些问题,它不喜欢创建 new Event(...),所以我们做了:

We had some issues getting this to work in Angular 2.1, it didn't like creating a new Event(...), so instead we did:

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();
}

这篇关于从 Angular 2 测试中更新输入 html 字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆