[英]How to iterate over and test different child elements within an element in cypress?
So, I have the elements in the following structure:所以,我有以下结构中的元素:
<div class="MuiBox-root" data-testid="all-events"> <ul....> <div class="MuiBox-root" data-testid="event"> <div class="MuiBox-root" data-testid="event"> <div class="MuiBox-root" data-testid="event">
Now, within each event element is the following structure:现在,在每个事件元素中都有以下结构:
<div class="MuiBox-root" data-testid="event"> <li.....> <div class="MuiBox-root....." data-testid="event-status"> <div> Text Value </div> <div class="MuiBox-root....." data-testid="event-name">
So, what I want to test is that if the element event-status is say completed or active, then the element event-name will be present.所以,我要测试的是,如果元素事件状态是已完成或活动,那么元素事件名称将存在。 So the approach that I am using is as follows:所以我使用的方法如下:
cy.get("[data-testid='events']").its("length").then((numEvents) => {
for (let i = 0; i < numEvents; i++) {
cy.get("[data-testid='event-status']").each((status, index) => {
if (index === i) {
if (isEventActive(status)) {
cy.get("[data-testid='event-name']").each((name, index) => {
if (index === i) {
cy.get(name).should("have.text", "some value");
}
});
} else {
cy.get("[data-testid='event-name']").each((name, index) => {
if (index === i) {
cy.get(name).should("not.exist");
}
});
}
}
});
}
});
The above code is working to test what I want to test out but it is incredibly messy and any simpler approaches are welcome.上面的代码正在测试我想要测试的内容,但它非常混乱,欢迎任何更简单的方法。
Convert the for loop to an .each()
.将 for 循环转换为.each()
。 Using .within()
on the event will allow internal get
commands to be specific to the event, and eliminate the need to check index values.在事件上使用.within()
将允许内部get
命令特定于事件,并消除检查索引值的需要。
cy.get("[data-testid='events']").each($event=> {
cy.wrap($event).within(() => {
cy.get("[data-testid='event-status']").each($status => {
if (isEventActive($status)) {
cy.get("[data-testid='event-name']").should("have.text", "some value");
}) else {
cy.get("[data-testid='event-name']").should("not.exist")
})
})
})
});
Maybe this will also work.也许这也会起作用。 Uses closure to get the two inner elements ($status and $name) into a ternary expression, and uses .should("satisfy", callbackFn)
to do an either/or check.使用闭包将两个内部元素($status 和 $name)放入三元表达式,并使用.should("satisfy", callbackFn)
进行非此即彼的检查。
cy.get("[data-testid='events']").each($event => {
cy.wrap($event).find("[data-testid='event-status']").then($status => {
cy.wrap($event).find("[data-testid='event-name']")
.should("satisfy", $name => isEventActive($status)
? $name.text() === "some value"
: $name.length === 0;
);
})
})
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.