javascript - 如何迭代和测试赛普拉斯元素中的不同子元素?
问题描述
所以,我有以下结构中的元素:
<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">
现在,在每个事件元素中都有以下结构:
<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">
所以,我要测试的是,如果元素事件状态是已完成或活动,那么元素事件名称将存在。所以我使用的方法如下:
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");
}
});
}
}
});
}
});
上面的代码正在测试我想要测试的内容,但它非常混乱,欢迎任何更简单的方法。
解决方案
Convert the for loop to an .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.
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.
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;
);
})
})
});
推荐阅读
- c++ - 仅使用必要的参数调用函数指针
- json - Elasticsearch 1.7.3:是否有任何聚合来计算术语聚合中有多少项?
- reactjs - 让 React 页面只对经过身份验证的用户可见?(使用 Django DRF 作为后端)
- javascript - ExtendScript 中的文件夹别名已损坏(Illustrator)
- javascript - IST时间格式在JS中返回NAN
- java - 不支持给定 DataStream 的类型:GenericType
弗林克卡桑德拉 - flutter - 无法使用 http 包将文件发送到服务器
- slack - Slack 上传文档
- c++ - 以特定于类的方式初始化对象
- python - 无法运行 jupyter-lab/jupyter-notebook