[英]Argument type string is not assignable to parameter type keyof Chainable ... cypress JS
[英]using cypress chainable command in if/else
如何將可鏈接命令與 if/else 邏輯混合使用? 任何人都知道如何清理代碼如下? 我不想重復代碼.trigger('focus', {force: true}).click({force: true});
在 if/else 中。 我能想到的唯一選擇是在邏輯中使用 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'));
}
您可以創建一個助手 function 來獲取正確的目標,
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});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.