相关疑难解决方法(0)

从Angular 2测试中更新输入html字段

我想在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中键入内容,以便使用用户在单元测试中输入的内容进行更新吗?

我可以毫无问题地抓住输入字段DebugElementnativeElement输入字段.(只是设置了value对房地产nativeElement的输入域的似乎并没有工作,因为它不更新ngModel什么我为值设置).

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

testing unit-testing jasmine angular

31
推荐指数
3
解决办法
3万
查看次数

角度测试:FormControl valueChanges Observable

我有一个文本输入,我正在听取更改.

零件

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字段 :测试表单输入值更改但没有运气:(

我错过了什么?

unit-testing jasmine karma-jasmine angular

6
推荐指数
1
解决办法
6073
查看次数

标签 统计

angular ×2

jasmine ×2

unit-testing ×2

karma-jasmine ×1

testing ×1