zl程序教程

您现在的位置是:首页 >  IT要闻

当前栏目

Cypress学习笔记6——Debugging调试代码

2023-02-26 10:14:56 时间

  引言

  我们写程序、写复杂的脚本时,如果遇到问题,经常需要打断点进行调式,而Cypress提供了很好的debug命令——debugger

  debugger调试器

  Cypress测试代码在与应用程序相同的运行循环中运行。这意味着您可以访问在页面上运行的代码,以及浏览器提供给您的内容,如document, window, and debugger。

  基于这些语句,您可能会试图在测试中添加调试器,如下所示:

/* __author__ = 'Leo' */



it('let me debug like a fiend', function() {
  cy.visit('https://www.baidu.com/')

  cy.get('#s-top-left')

  debugger // Doesn't work
})

  但是上面的代码并不会运行。Cypress 的文档里面介绍,cy命令是以队列的形式添加到列表里,最后才执行的。   debugger 将在 cy.visit() and cy.get() 之前执行,如下图。

   Let’s use .then() to tap into the Cypress command during execution and add a debugger at the appropriate time:

  让我们使用then()在执行过程中点击Cypress命令,并在适当的时候添加调试器:

it('let me debug when the after the command executes', () => {
  cy.visit('https://www.baidu.com/')

  cy.get('#s-top-left')
    .then(($selectedElement) => {
      // Debugger is hit after the cy.visit
      // and cy.get command have completed
      debugger
    })
})

  这样就可以先运行代码,在 debugger 位置暂停:

上面的代码整个工作流程如下

  • cy.visit()访问页面,Cypress等待加载
  • 查询该元素,如果没有立即找到它,Cypress会自动等待并重试一会儿。
  • 将执行传递给.then()的函数,并将找到的元素传递给它。
  • 在.then()函数的上下文中,调用 debugger 调试器,停止浏览器并调用 Developer Tools 的焦点。
  • 检查应用程序的状态,执行 debugger

  使用cy.debug()

Cypress还公开了用于调试命令的快捷方式.debug()。让我们用这个帮助器方法重写上面的测试:

it('let me debug like a fiend', function() {
  cy.visit('https://www.baidu.com/')

  cy.get('#s-top-left')
      .debug()
})

  此时 cy.get() 会生成一个 subject 变量,在 Developer Tools 里面可以直接使用 console 调试

 代码格式化一下:

it('let me debug like a fiend', function() {
  cy.visit('https://www.baidu.com/')
  cy.get('#s-top-left').debug()

})

在测试期间,使用.debug()快速检查应用程序的任何(或许多)部分。您可以将它附加到任何Cypress命令链上,以查看此时系统的状态。

  使用cy.pause()

  在调试代码时,除了用debug(),我们还有一个命令就是.pause()命令:

it('let me debug like a fiend', function() {
  cy.visit('https://www.baidu.com/')
    cy.pause()
    cy.get('#s-top-left')

})

  运行后:

  左上角有两个按钮,从左往右分别是

  • Resume:继续执行测试用例并运行到结束
  • Next:get:测试会变成逐步运行,点一下执行下一个命令

  总结

如果对python测试开发相关技术感兴趣的伙伴,欢迎加入测试开发学习交流QQ群:696400122,不积跬步,无以至千里。