我应该使用 wait() 来等待对话框关闭吗?有没有更好的办法?

Should I use wait() to wait for dialog to close? Is there a better way?

我想测试一下,当我单击关闭模态对话框的按钮 (ng material) 时,模态不存在。

这个测试实际上关闭了模态但是它通过了

it('should close the modal when the close button is clicked', () => {
            cy.get('#close-new-category').click();
            cy.get('#new-category').should('exist');
});

这个测试也有效

it('should close the modal when the close button is clicked', () => {
            cy.get('#close-new-category').click();
            cy.get('#new-category').should('not.exist');
});

这个测试失败,如果我加一个wait

it('should close the modal when the close button is clicked', () => {
                cy.get('#close-new-category').click();
                cy.wait(500);
                cy.get('#new-category').should('exist');
});

这个测试如我们预期的那样通过了,但是使用 wait() 是最好的方法吗?

it('should close the modal when the close button is clicked', () => {
            cy.get('#close-new-category').click();
            cy.wait(500);
            cy.get('#new-category').should('not.exist');
});

我问是因为文档说这是一个反模式,应该有更好的方法。

您不需要为这些测试使用 wait()。我认为这些示例测试过于像单元测试,而不够像端到端测试。

案例 #1 通过的原因是在单击关闭后模态仍然存在一小段时间。在这种情况下, should() 会立即检查并且仍然会看到您的模态,因此它会通过并继续前进。

案例 #2 也通过了,因为 should() 内置了重试逻辑,这是 cypress 的关键特性之一。单击关闭后,should() 立即检查并发现模态确实存在。因为找到模态,所以会等待重试。最终模态确实消失了,这个 should() 通过了。

出于测试场景的目的,您只需要关心案例 #2,因为它测试您的模态确实消失了。在 should() 通过之后,您可以在知道模态消失的情况下继续测试的下一步。它最初仍然存在的事实与您接下来要完成的事情无关紧要。