从Angular 2测试中更新输入html字段 [英] Updating input html field from within an Angular 2 test
问题描述
我想在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?
我可以获取 DebugElement
和输入字段的 nativeElement
没有问题。 (只是在输入字段的 nativeElement
上设置值
属性似乎不起作用,因为它没有'用我为该值设置的更新 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.
推荐答案
你是对的,你不能只设置输入,你还需要发送'输入'
事件。这是我今晚早些时候写的一个输入文本的函数:
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();
}
这里夹具
是 ComponentFixture
和 inputElement
是夹具的相关 HTTPInputElement
nativeElement
。这将返回一个承诺,因此您可能必须解决它 sendInput('whatever')。然后(...)
。
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(...)
.
更新:
我们在Angular 2.1中遇到了一些问题,它不喜欢创建一个新事件(...)
,所以我们做了:
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屋!