Prasad Parab
Prasad Parab

Reputation: 496

Angular unit test not respecting click event

I am writing a simple unit test for a element click '

Here is my html

<div *ngIf="!hidden" id='button'>
    <button
        [color]="'primary'"
        [disabled]="disabled"
        [label]="lablel"
        id="createButton"
        (click)="handleNextClick()"
        id='button'
    ></button>
</div>

Here is my unit test

it('should handleNextClick method called on button click', () => {
        let createsearchCreateDiv = fixture.debugElement.query(By.css('#button'));
        createsearchCreateDiv.nativeElement.click();



        fixture.whenStable().then(() => {
            expect(component.handleNextClick).toHaveBeenCalled();
        });

    });

My test case is passed irrespective of below line

createsearchCreateDiv.nativeElement.click();

Ideally it should not pass only if I remove/comment above line.

Method is not getting called if I remove/comment click. But still test case getting passed

Upvotes: 0

Views: 209

Answers (1)

Poul Kruijt
Poul Kruijt

Reputation: 71931

It's an async call, so you should use done, async/await or return the Promise:

it('should handleNextClick method called on button click', () => {
  // ...
  return fixture.whenStable().then(() => {
    expect(component.handleNextClick).toHaveBeenCalled();
  });
});

Upvotes: 1

Related Questions