如何检查该元素在赛普拉斯中具有任何一个类?

我们按如下方式搜索无效元素:


const invalidClasses = '.invalid, .invalid-default';


getInvalidElement() {

    cy.get(invalidClasses)

};

现在我有另一个函数,它接受该元素并检查它是否具有无效的类:


isInvalid(selector) {

 return cy.get(selector).should('have.class','invalid');

}

如何检查元素是否具有两个类中的任何一个?


我知道我能做到


cy.get(selector).invoke('attr','class').should('match','/invalid/');


但是,如果类别不同呢?


(此外,条件测试不适用于这种情况,无论是第一个类还是第二个类都没有逻辑,我们只是想要更多抽象的类进行重用)


DIEA
浏览 73回答 3
3回答

慕妹3146593

我想它会对你有用:cy.get('section') .should('have.class', 'container')

哔哔one

柏树包裹柴断言,所以从如何做一个“或”在柴应该.should()以下 html 片段<div id="1" class="class1"></div><div id="2" class="class2"></div><div id="3" class="class1 class2"></div><div id="4" class="class3"></div>可以像这样测试it('finds either class1 or class2', () => {&nbsp; cy.get('div#1')&nbsp; &nbsp; .should('satisfy', ($el) => {&nbsp; &nbsp; &nbsp; const classList = Array.from($el[0].classList);&nbsp;&nbsp; &nbsp; &nbsp; return classList.includes('class1') || classList.includes('class2') // passes&nbsp; &nbsp; })&nbsp;&nbsp; cy.get('div#2')&nbsp; &nbsp; .should('satisfy', ($el) => {&nbsp; &nbsp; &nbsp; const classList = Array.from($el[0].classList);&nbsp;&nbsp; &nbsp; &nbsp; return classList.includes('class1') || classList.includes('class2') // passes&nbsp; &nbsp; }) // passes&nbsp; cy.get('div#3')&nbsp; &nbsp; .should('satisfy', ($el) => {&nbsp; &nbsp; &nbsp; const classList = Array.from($el[0].classList);&nbsp;&nbsp; &nbsp; &nbsp; return classList.includes('class1') || classList.includes('class2') // passes&nbsp; &nbsp; })&nbsp;&nbsp; cy.get('div#4')&nbsp; &nbsp; .should('satisfy', ($el) => {&nbsp; &nbsp; &nbsp; const classList = Array.from($el[0].classList);&nbsp;&nbsp; &nbsp; &nbsp; return classList.includes('class1') || classList.includes('class2') // fails&nbsp; &nbsp; })&nbsp;})笔记函数的参数是一个jquery对象,因此用于引用元素$el[0]$el[0].classList返回一个类似数组的 DomTokenList,因此请使用将 Array 方法应用于它。Array.from().includes()您还可以通过提取函数使事情变得更加通用,it('finds either class1 or class2', () => {&nbsp; const hasAtLeastOneClass = (expectedClasses) => {&nbsp; &nbsp; return ($el) => {&nbsp; &nbsp; &nbsp; const classList = Array.from($el[0].classList);&nbsp;&nbsp; &nbsp; &nbsp; return expectedClasses.some(expectedClass => classList.includes(expectedClass));&nbsp; &nbsp; }&nbsp; }&nbsp; cy.get('div#1').should('satisfy', hasAtLeastOneClass(['class1', 'class2']));&nbsp; //passes&nbsp; cy.get('div#2').should('satisfy', hasAtLeastOneClass(['class1', 'class2']));&nbsp; //passes&nbsp; cy.get('div#3').should('satisfy', hasAtLeastOneClass(['class1', 'class2']));&nbsp; //passes&nbsp; cy.get('div#4').should('satisfy', hasAtLeastOneClass(['class1', 'class2']));&nbsp; //fails})

白猪掌柜的

Cypress应该提供和方法,它采用以前的主题(定位器),您可以应用尽可能多的条件和方法。cy.get('locator').should('have.class', 'validClassname').and('not.have.class', 'invalidClassname');我希望这将解决您的问题...投票这个答案以吸引更多人。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript