【发布时间】:2019-01-25 09:30:21
【问题描述】:
我有一个文本输入,我正在监听更改。
组件
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
});
}
HTML
<input name="name" formControlName="name">
到目前为止我的尝试:
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');
});
问题: 即使填充了输入字段,订阅回调中的代码也永远不会执行。
它总是显示:
预期的“旧值”是“新值”。
我也尝试了setValue() 方法,但没有成功。它永远不会进入订阅回调
app.name.setValue('vikas');
fixture.detectChanges();
fixture.whenStable().then(()=>{expect(app.data).toBe('newvalue');
我提到了Updating input html field from within an Angular 2 test 和Angular2 Component: Testing form input value change 但没有运气:(
我错过了什么?
【问题讨论】:
标签: angular unit-testing jasmine karma-jasmine