是否有可能等待直到某个元素可见?
cy.get('[data-test=submitIsVisible]').should('be.visible');
如果提交按钮不可见,那么这应该会出错。我想等待提交按钮变为可见。
主要用例是视觉测试,即对页面进行截图。
是否有可能等待直到某个元素可见?
cy.get('[data-test=submitIsVisible]').should('be.visible');
如果提交按钮不可见,那么这应该会出错。我想等待提交按钮变为可见。
主要用例是视觉测试,即对页面进行截图。
// Give this element 10 seconds to appear
cy.get('[data-test=submitIsVisible]', { timeout: 10000 }).should('be.visible');
DOM
的命令将在失败之前自动重试并等待其对应的元素存在。DOM
的方法,所有这些方法都包含了重试和超时逻辑。DOM
中出现的方法是通过超时
。 Cypress命令默认超时时间为4秒,但大多数Cypress命令都有可定制的timeout
选项。超时可以在全局或每个命令的基础上进行配置。 在此处查看可定制的timeout
选项列表here。
有些情况下,你的DOM
元素可能无法被执行。Cypress为你提供了一个强大的{force:true}
选项,你可以将其传递给大多数动作命令。
警告:
正如Anthony Cregan所指出的那样,.should('be.visible')
断言检查一个元素是否在页面上可见,但不一定在视口中。这意味着即使在测试运行时元素不在屏幕的可见区域内,该断言也会返回true。
更多推荐阅读:
如果你想了解Cypress如何等待某个元素变得可见,可以参考以下示例。
通过这段代码,你可以测试delay
和timeout
如何影响.should('be.visible')
断言的结果。
Add a simple page to a VSCode project containing Cypress v12.1.0
Call it index.html
<html>
<body>
<h2>API fetched data</h2>
<span>will become visible here</span>
</body>
<script>
fetch('https://jsonplaceholder.typicode.com/posts/1')
.then(response => response.json())
.then(data => document.querySelector('span').innerText = data.title )
</script>
</html>
Right-click index.html
and choose "Open with Live Server" to activate the page.
Add this test to see how Cypress waits for the API data
describe('test the waiting of API data', () => {
const timings = [
{ delay: 0, timeout: 4000 }, // default, passes
{ delay: 2000, timeout: 4000 }, // passes
{ delay: 4000, timeout: 4000 }, // flaky
{ delay: 5000, timeout: 4000 }, // fails
{ delay: 5000, timeout: 10000 }, // passes
]
timings.forEach(timing => {
const {delay, timeout} = timing;
it(`delayed API by ${delay} ms, command timout is ${timeout} ms`, () => {
cy.intercept('https://jsonplaceholder.typicode.com/posts/1', (req) => {
req.continue((res) => res.setDelay(delay))
})
cy.visit('http://127.0.0.1:5500/index.html')
cy.contains('sunt aut facere', {timeout})
.should('be.visible')
})
})
})
这表明接收数据的延迟越长,可见性断言所需的超时时间就越大。
您也可以通过将以下脚本传递到cypress.config.js文件中来完成此操作
e2e: {
defaultCommandTimeout: 25000,
}
根据您的需求传递defaultCommandTimeout
。
element.should('have.length.greaterThan', 0).and('be.visible')
。