I have a text input and I'm listening for the changes.
component
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">
My Attempt so far:
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');
});
Problem: Even though input field is populated the code inside subscribe callback is never executed.
It always shows:
Expected 'oldvalue' to be 'newvalue'.
I tried setValue()
method too but it did not work. it never goes inside subscribe callback
app.name.setValue('vikas');
fixture.detectChanges();
fixture.whenStable().then(()=>{expect(app.data).toBe('newvalue');
I referred Updating input html field from within an Angular 2 test and Angular2 Component: Testing form input value change but no luck :(
What am I missing?