开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第8天,点击查看活动详情
大家好,我是阿萨。上一期的cypress 我们学习了如何写常见用例。cypress原生支持截图和录制视频。今天我们就学习下cypress如何截图。
screenshot
就是给某个对象截图。一共有三四个方法,带不同的参数,不同的文件名称和选项。
.screenshot()
.screenshot(fileName)
.screenshot(options)
.screenshot(fileName, options)
// ---or---
cy.screenshot()
cy.screenshot(fileName)
cy.screenshot(options)
cy.screenshot(fileName, options)
常见用法:
直接截图,整个桌面截图,或者某个post响应的截图。
cy.screenshot()
cy.get('.post').screenshot()
截图默认保存在cypress/screenshots文件夹中。可以在Cypress配置中更改截图保存的目录。
// cypress/e2e/users.cy.js
describe('Sarah’s screenshot tests', () => {
it('takes a screenshot', () => {
// 截图保存在
// cypress/screenshots/users.cy.js/my tests -- takes a screenshot.png
cy.screenshot() })})
文件名截取一个截图并保存为一个特定的文件名。给截图的文件取一个特殊的名字。
// 截图保存在// cypress/screenshots/spec.cy.js/clicking-on-nav.png
cy.screenshot('clicking-on-nav')
截图并保存到特定目录, 选择相对路径去保存截图。
// 截图保存在// cypress/screenshots/spec.cy.js/actions/login/clicking-login.png
cy.screenshot('actions/login/clicking-login')
裁剪裁剪截图到一个特定的位置和大小
把截图裁剪成大小合适的截图。
//截图将从顶部和左侧裁剪20px//设置尺寸为400px x 300pxcy.screenshot({ clip: { x: 20, y: 20, width: 400, height: 300 } })
截图一个元素截取第一个.post元素的截图
cy.get('.post').first().screenshot()
截取第一个。post元素的截图,周围填充10px
cy.get('.post').first().screenshot({ padding: 10 })
链接截图,单击捕获的元素
cy.get('button').first().screenshot().click()
从onafter截图回调中获取截图信息
cy.screenshot('my-screenshot', {
onAfterScreenshot($el, props) {
// props has information about the screenshot,
// including but not limited to the following://
{
name: 'my-screenshot',
path: '/Users/janelane/project/screenshots/spec.cy.js/my-screenshot.png',
size: '15 kb',
dimensions: {
width: 1000,
height: 660,
},
scaled: true,
blackout: [],
duration: 2300,
} },})
今天的截图,你学会了。如果你喜欢阿萨的内容,欢迎围观和点赞。