Home > OS >  While testing angular app for the functionality "when button is clicked the count will be incre
While testing angular app for the functionality "when button is clicked the count will be incre

Time:09-23

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?.

CodePudding user response:

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;
})

CodePudding user response:

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
      const btn = debug.query(By .css('#button1'));
      btn.triggerEventHandler('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);
    })
  • Related