Home > other >  How to check if alert has been called?
How to check if alert has been called?

Time:09-22

I am testing my Angular application, I currently I want to check if alert has showed up after clicking on a button. I have the following code:

it('should display alert when clicking on icon', () => {
  const button = fixture.nativeElement.querySelector('.pi-trash');
  button.click();
  spyOn(window, 'alert').and.callThrough();
  expect(window.alert).toHaveBeenCalledWith('delete');
})

An alert is created with a message 'delete' and in the logs I can see: "ALERT: delete", but test is failing with an error: Expected spy alert to have been called with: [ 'delete' ] but it was never called.

Can someone tell me what I am missing? Thanks!

CodePudding user response:

Just so this question can be closed successfully. Here is the answer: spyOn(window, 'alert').and.callThrough(); has to be moved to the beginning of the test. In your case window.alert was only spied on after it was already called.

  • Related