如何断言没有出现警报?

How to assert that an alert does not appear?

当某个 UI 错误出现时,会弹出一个带有错误消息的警报。我修复了那个错误,现在我想写一个 Cypress 测试。


如果没有出现警报,我该如何编写一个通过的 Cypress 测试?

我意识到我必须 be careful with negative assertions,所以我想尽可能使测试稳健。


相关post:

How do I write a Cypress test that passes if the alert does not appear?


  1. Spy on the window:alert event.
  2. 等待几秒钟,让警报有时间出现。
  3. 使用肯定的断言来确保间谍是您所期望的。
  4. 断言间谍未被调用。
// Typing enter should not produce an alert
let spy = cy.spy(window, 'alert');
cy.get('input[name="MyField"]')
    .type('{enter}')
    .wait(4000)
    .then(() => {
        expect(spy).to.haveOwnProperty('callCount');
        expect(spy).to.not.be.called;
    });
  1. 也对错误修复后应该发生的任何事情做出肯定的断言。