0

When button is clicked the count will be incremented and at the same time the count will be displayed in the html page in angular. For this condition I wrote the unit test using jasmine + Karma runner. But the expected value is not equal.

In testing : debug element module is used.

html code:

<button id="button1" (click)="count()">Click</button>
<h2>{{cnt}}</h2>

ts code:

cnt:number = 0;
count()
{
  this.cnt+=1;
}

spec file:

it("check events with debugelement",()=>{
      const fixture = TestBed.createComponent(AppComponent);
      debug = fixture.debugElement;
      const h2 = debug.query(By .css('h2'));
      const btn = debug.query(By .css('#button1'));
      btn.triggerEventHandler('click',{});
      fixture.detectChanges();
      let x = component.cnt;
      let y = parseInt(h2.nativeElement.innerText);
      expect(x).toBe(y);
    })

error:

Expected 0 to be 1.

"I am getting different values". Can I know what mistake I have done?.

RobC
  • 22,977
  • 20
  • 73
  • 80

2 Answers2

0

The code you have posted is not having any error

Instead of defining fixture inside the it() block you can use beforeEach

beforeEach(() => {
  // code executed before every 'it' block
  const fixture = TestBed.createComponent(AppComponent);
  component = fixture.componentInstance;
})

Also assign component variable with fixture.componentInstance

Bharath S
  • 364
  • 4
  • 10
0

The mistake is that you're querying for h2's value too early.

Follow my comments for a detailed explanation.

it("check events with debugelement",()=>{
      const fixture = TestBed.createComponent(AppComponent);
      debug = fixture.debugElement;
      const h2 = debug.query(By .css('h2'));
      // h2's value here is 0
      // !! change the following 2 lines !!
      const btn = debug.query(By .css('#button1')).nativeElement;
      btn.click();
      fixture.detectChanges();
      let x = component.cnt;
      let y = parseInt(h2.nativeElement.innerText);
      // y is zero here since you didn't query for the new/updated h2
      const updatedh2 = debug.query(By.css('h2'));
      let z = parseInt(updatedh2.nativeElement.innerText);
      // z should be one now
      expect(x).toBe(z);
    })
AliF50
  • 16,947
  • 1
  • 21
  • 37
  • h2 value is working fine but the value of the variable x is zero even after triggering the event of the click . result: x = 0 & z =1 . – ugenthar V Sep 23 '21 at 08:19
  • Ok, check my edits. Try using `btn.click()` instead of `triggerEventHandler`. – AliF50 Sep 23 '21 at 12:36
  • Yeah it works fine with the click but it fails for `triggerEventHandler` can I know the reason why it isn't working ? – ugenthar V Sep 24 '21 at 05:21
  • I think this answer explains it: https://stackoverflow.com/a/46445291/7365461 – AliF50 Sep 24 '21 at 12:58