如何使用与if/else逻辑混合的可链接命令?有人知道如何清理以下代码吗?我不想在if/else中都有重复的代码.trigger('focus', {force: true}).click({force: true});
。我唯一能想到的选择就是在逻辑中使用return。但不起作用
const selectedOption = 'I am option'
cy.get('.my-selector')
.contains(selectedOption)
.scrollIntoView()
.then(($option) => {
if ($option.find('input').length === 1) {
cy.wrap($option.find('input')).trigger('focus', {force: true}).click({force: true});
} else {
cy.wrap($option).trigger('focus', {force: true}).click({force: true});
}
});
使用return
.then(($option) => {
if ($option.find('input').length === 1) {
return cy.wrap($option.find('input'));
}
您可以创建一个助手函数来获得正确的目标
const getTarget = ($el) => {
const $input = $el.find('input');
return $input.length ? $input : $el;
}
cy.get('.my-selector')
.contains(selectedOption)
.scrollIntoView()
.then(($option) => {
cy.wrap(getTarget($option)).trigger('focus', {force: true}).click({force: true});
});
// another syntax
cy.get('.my-selector')
.contains(selectedOption)
.scrollIntoView()
.then($option => getTarget($option))
.trigger('focus', {force: true}).click({force: true});
或者使用自定义命令
Cypress.Commands.add('optionTarget', { prevSubject: true }, (subject) => {
const $input = subject.find('input');
return $input.length ? $input : subject;
})
cy.get('.my-selector')
.contains(selectedOption)
.scrollIntoView()
.optionTarget().trigger('focus', {force: true}).click({force: true});