因此,我正在编写一个测试,将一张卡添加到容器(支付卡容器)中,我想通过查看子元素是否增加了 1 来确认稍后添加了一个元素。但是当我们尝试添加元素时,我遇到了问题当没有孩子时,计算孩子的长度。我目前正在使用以下内容:
cy.get('[data-test-id="payment-card-container"]')
.children()
.its('length')
.then(length => {
const childrenLength = length;
})
Run Code Online (Sandbox Code Playgroud)
但是 Cypress 似乎遇到错误,因为它找不到子级(错误如下)。
Timed out retrying: Expected to find element: ``, but never found it.
Run Code Online (Sandbox Code Playgroud)
当没有任何孩子并且返回值 0 时,有没有一种方法可以工作?
小智 7
使用像这样的 jQuery 表达式的问题
Cypress.$('[data-test-id="payment-card-container"]').children().length
Run Code Online (Sandbox Code Playgroud)
是你没有得到赛普拉斯重试异步更新。
如果添加支付卡调用 API,则上述表达式将错误报告 0 个子项,而不是等待 DOM 更新。
确实没有什么好的办法来处理无卡的情况,
除了
如果您必须测试零个子项,则尾随.should()将删除错误消息。
cy.get('[data-test-id="payment-card-container"]')
.children()
.should('have.length', 0); // no error when should expression passes
// Add card here
cy.get('[data-test-id="payment-card-container"]')
.children()
.should('have.length', 1); // waits for async add-card operation
Run Code Online (Sandbox Code Playgroud)
测试用
<body>
<div data-test-id="payment-card-container"></div>
<script>
setTimeout(() => {
const div = document.querySelector('[data-test-id="payment-card-container"]');
const p = document.createElement('p')
div.appendChild(p)
}, 2000)
</script>
</body>
Run Code Online (Sandbox Code Playgroud)