背景

  • 在测试运行时截图和录屏能够在测试错误时快速定位到问题所在
  • Cypress 截图和录屏功能强大

无须配置,自动截图

以 cypress run 方式运行测试时,当测试发生错误时,Cypress 会自动截图,并默认保存在 cypress/screenshots 文件夹下,而录屏会保存在 cypress/video 文件夹下

命令行运行结果

Cypress系列(60)- 运行时的截图和录屏,screenshot() 命令详解 - 图1
console 会看到错误截图和录屏的生成路径

生成截图和录屏的目录

Cypress系列(60)- 运行时的截图和录屏,screenshot() 命令详解 - 图2

自定义截图,.screenshot() 方法

作用

截取被测应用程序的屏幕快照,以及 Cypress 命令日志的屏幕快照

语法格式

  1. .screenshot()
  2. .screenshot(fileName)
  3. .screenshot(options)
  4. .screenshot(fileName, options)
  5. // ---or---
  6. cy.screenshot()
  7. cy.screenshot(fileName)
  8. cy.screenshot(options)
  9. cy.screenshot(fileName, options)

fileName

  • 待保存图片的名称
  • 图片默认保存在 cypress/screenshots 文件夹下,可以在 cypress.json 修改默认文件夹路径(配置项 screenshotsFolder )

options 详解

Cypress系列(60)- 运行时的截图和录屏,screenshot() 命令详解 - 图3
Cypress系列(60)- 运行时的截图和录屏,screenshot() 命令详解 - 图4
通过 onBeforeScreenshot、onAfterScreenshot,可以在截图发生前或发生后应用自定义的行为

正确用法

  1. // 直接截图整个页面
  2. cy.screenshot()
  3. // 只截图某个特定元素
  4. cy.get('.post').screenshot()

命令返回结果

返回上一条命令相同的结果

.screenshot() 栗子

测试代码

  1. it('简单的栗子', function () {
  2. // 截图整个页面
  3. cy.screenshot()
  4. });

测试结果

Cypress系列(60)- 运行时的截图和录屏,screenshot() 命令详解 - 图5
为什么截图这么长呢?
因为 capture 默认值就是 fullpage,代表整个页面

.screenshot(filename) 栗子

测试代码

  1. it('文件名', function () {
  2. cy.screenshot('文件名')
  3. });

测试结果

Cypress系列(60)- 运行时的截图和录屏,screenshot() 命令详解 - 图6

.screenshot(options) 栗子

capture:viewport 的栗子

测试代码

  1. cy.screenshot({
  2. capture: 'viewport'
  3. })

测试结果

Cypress系列(60)- 运行时的截图和录屏,screenshot() 命令详解 - 图7

capture:runner 的栗子

测试代码

  1. cy.screenshot({
  2. capture: 'runner'
  3. })

测试结果

Cypress系列(60)- 运行时的截图和录屏,screenshot() 命令详解 - 图8

.screenshot() 命令日志

Cypress系列(60)- 运行时的截图和录屏,screenshot() 命令详解 - 图9
可以看到各配置项(options)的默认值

onBeforeScreenshot 的栗子

截图某个元素

测试代码

Cypress系列(60)- 运行时的截图和录屏,screenshot() 命令详解 - 图10

测试结果

Cypress系列(60)- 运行时的截图和录屏,screenshot() 命令详解 - 图11
$el 是当前元素

截图结果

Cypress系列(60)- 运行时的截图和录屏,screenshot() 命令详解 - 图12

截图整个页面

测试代码

Cypress系列(60)- 运行时的截图和录屏,screenshot() 命令详解 - 图13

测试结果

Cypress系列(60)- 运行时的截图和录屏,screenshot() 命令详解 - 图14
$el 是页面根标签

onAfterScreenshot 的栗子

截图某个元素

测试代码

Cypress系列(60)- 运行时的截图和录屏,screenshot() 命令详解 - 图15

测试结果

Cypress系列(60)- 运行时的截图和录屏,screenshot() 命令详解 - 图16
可以看到 props 是当前的一些属性,后面有需要可以获取对应的属性值(格式:props.path)

onAfterScreenshot 源码

Cypress系列(60)- 运行时的截图和录屏,screenshot() 命令详解 - 图17
可以看到不同属性的数据类型

待补充知识点链接
https://docs.cypress.io/api/commands/screenshot.html#after-screenshot-plugin-event

https://www.cnblogs.com/poloyy/p/13743099.html