我有一个 Nextjs 项目,它使用 Percy(与 Cypress 集成)来运行可视化测试。我的项目从 CMS 获取图像。如何确保页面上的所有图像在(拍摄快照)或检查元素之前已加载?
我看过一个检查损坏图像的示例
const brokenImages = []
cy.get('img')
.each(($el, k) => {
if ($el.prop('naturalWidth') === 0) {
const id = $el.attr('id')
const alt = $el.attr('alt')
const info = `${id ? '#' + id : ''} ${alt ? alt : ''}`
brokenImages.push(info)
cy.log(`Broken image ${k + 1}: ${info}`)
}
})
.then(() => {
// report all broken images at once
// enable the condition to see the thrown error
if (false && brokenImages.length) {
throw new Error(
`Found ${
brokenImages.length
} broken images\n${brokenImages.join(', ')}`,
)
}
})
另一个检查单个图像的自然宽度(这在 Nextjs 中不起作用
cy.get('#loads')
.should('be.visible')
.and('have.prop', 'naturalWidth')
.should('be.greaterThan', 0)
我是否需要等待一定的秒数并希望它们已加载?
属性
naturalWidth
是 javascript 原生的,不应受到 NextJs 框架的影响,<img>
都应返回非零的naturalWidth 属性。
但是,图像可能会延迟加载,在这种情况下
.scrollIntoView()
可能会解决您的问题。
我在精选的 Nextjs 示例页面上运行了此测试,它们都通过了
describe('nextjs img loading examples', () => {
const sites = [
'https://image-component.nextjs.gallery/',
'https://app-router-contentful.vercel.app/',
'https://next-blog-prismic.vercel.app/',
'https://next-blog-umbraco-heartcore.vercel.app/'
]
sites.forEach(site => {
it(`verifies images for ${site}`, () => {
cy.visit(site);
cy.get('img').each(img => {
cy.wrap(img)
.scrollIntoView()
.its('0.naturalWidth') // Note "0" extracts element from jQuery wrapper
.should('be.greaterThan', 0)
})
})
})
})