使用 Cypress 处理警告
与 Selenium 或 Protractor 等其他自动化工具不同,Cypress 有一种独特的方式来处理警告。Cypress 基本上会自动接受警告,我们无需编写逻辑来处理它们。
弹出窗口有两种类型:警告弹出窗口(只有“确定”按钮)和确认弹出窗口(有“确定”和“取消”按钮)。Cypress 的设计使得它会在弹出窗口上点击“确定”按钮,无需任何手动干预。它具有触发浏览器事件的功能。
示例
处理警告的代码实现。
describe('Tutorialspoint Test', function () { // test case it('Test Case3', function (){ // launch the url cy.visit("https://register.rediff.com/register/register.php?FormName=user_details"); // click on submit button to produce the alert pop up cy.get('input[type="submit"]').click(); }); });
在执行上述代码时,我们没有发现任何警告的出现,因为测试用例正在运行,但是测试日志清楚地显示了警告消息的证据。
现在如何验证警告弹出窗口上的文本?浏览器在弹出窗口打开时会触发一个 **window: alert** 事件。此事件可用于验证警告文本。Cypress 默认情况下会接受此警告,并且我们无法在不触发浏览器事件的情况下修改此行为。
Cypress 将使用 on() 方法触发 **window:alert** 事件,然后捕获警告上的文本(稍后可以通过断言进行验证),但整个事件将不会在屏幕上显示。
示例
警告文本验证的代码实现。
describe('Tutorialspoint Test', function () { // test case it('Test Case3', function (){ // launch the url cy.visit("https://register.rediff.com/register/register.php?FormName=user_details"); // click on submit button to produce the alert pop up cy.get('input[type="submit"]').click(); // firing window: alert event with on() method cy.on('window:alert',(txt)=>{ //Mocha assertions expect(txt).to.contains('Your full name cannot be blank.'); }) }); });
通过检查测试运行程序日志,我们将找到警告弹出窗口的详细信息。
现在如何验证确认警告弹出窗口上的文本?浏览器在确认弹出窗口打开时会触发一个 **window: confirm** 事件。此事件将返回 false 以取消确认。Cypress 默认情况下会接受确认。
Cypress 将使用 on() 方法触发 **window:confirm** 事件,然后捕获警告上的文本(稍后可以通过断言进行验证),但整个事件将不会在屏幕上显示。
Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.
示例
确认弹出窗口文本验证的代码实现。
describe('Tutorialspoint Test', function () { // test case it('Test Case3', function (){ // launch the url cy.visit("https://tutorialspoint.com/selenium /selenium_automation_practice.htm"); // click on submit button to produce the confirmation alert pop up cy.get('button[name="submit"]').click(); // firing window: alert event with on() method cy.on('window:confirm',(txt)=>{ //Mocha assertions expect(txt).to.contains('You are submitting information to an external page.'); }) }); });
通过检查测试运行程序日志,我们将找到确认弹出窗口的详细信息。