2

I'm trying to test event which value entering by keyboard. my problem is after set value to the input field, when I print it prints, but when I print it inside the whenStable() it prints empty. I want to know why this value gets reset inside of the Whitstable() function. and how can I fix it?

I have referred: Updating input html field from within an Angular 2 test to write this test case.

it('Test input field value. ', async () => {
    const divDescription = fixture.debugElement.query(By.css('#costDescription'));

    divDescription.nativeElement.value = 'text';
    divDescription.nativeElement.dispatchEvent(new Event('input'));
    fixture.detectChanges();
    console.log('sendInput : ', divDescription.nativeElement.value); // prints 'text'
    fixture.whenStable().then(() => {
      console.log('sendInput : ', divDescription.nativeElement.value); // prints ''
      expect(divDescription.nativeElement.value).toContain('text');
    });
  });
bugfreerammohan
  • 1,471
  • 1
  • 7
  • 22
Sachithra Wishwamal
  • 117
  • 1
  • 2
  • 10

2 Answers2

4

Removing WhenStable() make this happens.

  it('Test input field value. ', async () => {
      const divDescription = fixture.debugElement.query(By.css('#costDescription'));
      divDescription.nativeElement.value = 'text';
      divDescription.nativeElement.dispatchEvent(new Event('input'));
      fixture.detectChanges();
      expect(divDescription.nativeElement.value).toContain('text');
  });
Sachithra Wishwamal
  • 117
  • 1
  • 2
  • 10
  • The code above works as shown, however should I be seeing this content in the Jasmine runner which is hosting the Angular 7 application. The field values don't change in browser? – JWP Apr 24 '19 at 16:31
  • IMHO, this test actually pointless since all you are doing is testing the value of the thing you just set. A better test would be to ensure the change in the input field is also reflected in your model. –  Sep 09 '19 at 18:55
1

you have to move Change detection call inside wheStable

it('Test input field value. ', async () => {
 const divDescription = fixture.debugElement.query(By.css('#costDescription'));

 divDescription.nativeElement.value = 'text';
 divDescription.nativeElement.dispatchEvent(new Event('input'));

 console.log('sendInput : ', divDescription.nativeElement.value); // prints 'text'
 fixture.whenStable().then(() => {
  fixture.detectChanges(); // moved inside
  console.log('sendInput : ', divDescription.nativeElement.value); 
  expect(divDescription.nativeElement.value).toContain('text');
 });
});
Fateh Mohamed
  • 20,445
  • 5
  • 43
  • 52