简体   繁体   English

如何检查是否已调用警报?

[英]How to check if alert has been called?

I am testing my Angular application, I currently I want to check if alert has showed up after clicking on a button.我正在测试我的 Angular 应用程序,我目前想检查单击按钮后是否出现警报。 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!谢谢!

Just so this question can be closed successfully.就这样这个问题可以成功关闭。 Here is the answer: spyOn(window, 'alert').and.callThrough();这是答案: 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.在您的情况下, window.alert仅在已被调用后才被监视。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM