Cypress系列(60)- 運行時的截圖和錄屏,screenshot() 命令詳解


如果想從頭學起Cypress,可以看下面的系列文章哦

https://www.cnblogs.com/poloyy/category/1768839.html

 

背景

  • 在測試運行時截圖和錄屏能夠在測試錯誤時快速定位到問題所在
  • Cypress 截圖和錄屏功能強大

 

無須配置,自動截圖

以 cypress run 方式運行測試時,當測試發生錯誤時,Cypress 會自動截圖,並默認保存在 cypress/screenshots 文件夾下,而錄屏會保存在 cypress/video 文件夾下

 

命令行運行結果

console 會看到錯誤截圖和錄屏的生成路徑

 

生成截圖和錄屏的目錄

 

自定義截圖,.screenshot() 方法

作用

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

 

語法格式

.screenshot()
.screenshot(fileName)
.screenshot(options)
.screenshot(fileName, options)

// ---or---

cy.screenshot()
cy.screenshot(fileName)
cy.screenshot(options)
cy.screenshot(fileName, options)

 

fileName

  • 待保存圖片的名稱
  • 圖片默認保存在 cypress/screenshots 文件夾下,可以在 cypress.json 修改默認文件夾路徑(配置項 screenshotsFolder )

 

options 詳解

通過 onBeforeScreenshot、onAfterScreenshot,可以在截圖發生前或發生后應用自定義的行為

 

正確用法

// 直接截圖整個頁面
cy.screenshot()

// 只截圖某個特定元素
cy.get('.post').screenshot()

 

命令返回結果

返回上一條命令相同的結果

 

.screenshot() 栗子

測試代碼

it('簡單的栗子', function () {
    // 截圖整個頁面
    cy.screenshot()
});

 

測試結果

為什么截圖這么長呢?

因為 capture 默認值就是 fullpage,代表整個頁面

 

.screenshot(filename) 栗子

測試代碼

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

 

測試結果

 

.screenshot(options) 栗子

capture:viewport 的栗子

測試代碼

cy.screenshot({
     capture: 'viewport'
})

 

測試結果

 

capture:runner 的栗子

測試代碼

cy.screenshot({
     capture: 'runner'
})

 

測試結果

 

.screenshot() 命令日志

 可以看到各配置項(options)的默認值

 

onBeforeScreenshot 的栗子

截圖某個元素

測試代碼

 

測試結果

$el 是當前元素

 

截圖結果

 

截圖整個頁面

測試代碼

 

測試結果

$el 是頁面根標簽

 

onAfterScreenshot 的栗子

截圖某個元素

測試代碼

 

測試結果

可以看到 props 是當前的一些屬性,后面有需要可以獲取對應的屬性值(格式:props.path)

 

onAfterScreenshot 源碼

可以看到不同屬性的數據類型

 

待補充知識點鏈接

https://docs.cypress.io/api/commands/screenshot.html#after-screenshot-plugin-event


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM