我想在Angular 2单元测试中更改输入字段的值.
<input type="text" class="form-control" [(ngModel)]="abc.value" />
Run Code Online (Sandbox Code Playgroud)
我不能只改变ngModel因为abc对象是私有的:
private abc: Abc = new Abc();
Run Code Online (Sandbox Code Playgroud)
在Angular 2测试中,我可以模拟用户在输入字段ngModel中键入内容,以便使用用户在单元测试中输入的内容进行更新吗?
我可以毫无问题地抓住输入字段DebugElement和nativeElement输入字段.(只是设置了value对房地产nativeElement的输入域的似乎并没有工作,因为它不更新ngModel什么我为值设置).
也许inputDebugEl.triggerEventHandler可以被调用,但是我不确定给它的参数是什么它将模拟用户输入特定的输入字符串.
我有一个文本输入,我正在听取更改.
零件
name = new FormControl('',Validators.required);
ngOnInit() {
this.data = 'oldvalue';
this.checkName();
}
checkName() {
this.name.valueChanges.subscribe(val=>{
console.log(val);
this.data= "newvalue"; // updating Value
});
}
Run Code Online (Sandbox Code Playgroud)
HTML
<input name="name" formControlName="name">
Run Code Online (Sandbox Code Playgroud)
到目前为止我的尝试:
component.spec.ts
it('should test data field ', () => {
const fixture = TestBed.createComponent(UserComponent);
const app=fixture.debugElement.componentInstance;
const el = fixture.nativeElement.querySelector('input');
el.value ='something';
dispatchEvent(new Event(el));
fixture.detectChanges();
fixture.whenStable().then(()=>{expect(app.data).toBe('newvalue');
});
Run Code Online (Sandbox Code Playgroud)
问题: 即使填充了输入字段,也不会执行subscribe回调中的代码.
它总是显示:
预期'oldvalue'为'newvalue'.
我也尝试了setValue()方法,但它没有用.它永远不会进入订阅回调
app.name.setValue('vikas');
fixture.detectChanges();
fixture.whenStable().then(()=>{expect(app.data).toBe('newvalue');
Run Code Online (Sandbox Code Playgroud)
我在Angular 2测试和Angular2组件中引用了更新输入html字段 :测试表单输入值更改但没有运气:(
我错过了什么?