分享

Cypress web自动化27-Debugging调试你的代码

 上海悠悠 2021-05-27

前言

在写脚本的过程中,有时候会遇到一些问题需要慢慢调试找出原因,Cypress 提供了调试的方法,方便我们快速定位到问题

debugger 调试器

你的Cypress测试代码运行在与应用程序相同的运行循环中.这意味着你可以访问页面上运行的代码, 以及浏览器为你提供的东西, 比如document, window等等, 当然也包括调试器.

基于这些陈述, 你可能想在测试中添加一个 debugger 调试器, 就像这样:

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

cy.get('#blog_nav_sitehome')

debugger // Doesn't work
})

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

我们可以使用 .then()在执行期间进入 Cypress 命令,并在适当的时间添加调试器

it('let me debug when the after the command executes', function () {
cy.visit('https://www.cnblogs.com/yoyoketang/')

cy.get('#blog_nav_sitehome')
.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

使用 .debug()

Cypress 通过了一个 .debug() 方法,可以直接调用,更省事!

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

cy.get('#blog_nav_sitehome')
.debug()
})

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

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

    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多