diff --git a/docs/locators.md b/docs/locators.md index 2349bc705..d8c1a266e 100644 --- a/docs/locators.md +++ b/docs/locators.md @@ -145,6 +145,15 @@ Find an element with provided attributes locate('input').withAttr({ placeholder: 'Type in name' }); ``` +#### withClassAttr + +Find an element with class attribute + +```js +// find div with class contains 'form' +locate('div').withClassAttr('text'); +``` + #### withChild Finds an element which contains a child element provided: diff --git a/lib/locator.js b/lib/locator.js index 1cffebb24..1c958b9d9 100644 --- a/lib/locator.js +++ b/lib/locator.js @@ -299,6 +299,15 @@ class Locator { return new Locator({ xpath }); } + /** + * @param {String} text + * @returns {Locator} + */ + withClassAttr(text) { + const xpath = sprintf('%s[%s]', this.toXPath(), `contains(@class, '${text}')`); + return new Locator({ xpath }); + } + /** * @param {string} output * @returns {Locator} diff --git a/test/helper/webapi.js b/test/helper/webapi.js index 4795f351e..413e95037 100644 --- a/test/helper/webapi.js +++ b/test/helper/webapi.js @@ -1390,11 +1390,11 @@ module.exports.tests = function () { try { await I.amOnPage('https://github.com/codeceptjs/CodeceptJS/'); - await I.seeAttributesOnElements({ css: 'a[href="/team"]' }, { - href: '/team', + await I.seeAttributesOnElements({ css: 'a[href="/codeceptjs/CodeceptJS"]' }, { + href: '/codeceptjs/CodeceptJS', }); } catch (e) { - e.message.should.include('all elements (a[href="/team"]) to have attributes {"href":"/team"}'); + e.message.should.include('all elements (a[href="/codeceptjs/CodeceptJS"]) to have attributes {"href"="/codeceptjs/CodeceptJS"}'); } }); @@ -1425,11 +1425,11 @@ module.exports.tests = function () { try { await I.amOnPage('https://github.com/codeceptjs/CodeceptJS/'); - await I.seeAttributesOnElements({ css: 'a[href="/team"]' }, { + await I.seeAttributesOnElements({ css: 'a[href="/codeceptjs/CodeceptJS"]' }, { disable: true, }); } catch (e) { - e.message.should.include('expected all elements ({css: a[href="/team"]}) to have attributes {"disable":true} "0" to equal "1"'); + e.message.should.include('expected all elements ({css: a[href="/codeceptjs/CodeceptJS"]}) to have attributes {"disable":true} "0" to equal "3"'); } }); diff --git a/test/unit/locator_test.js b/test/unit/locator_test.js index cc8d1a382..dc21a19bf 100644 --- a/test/unit/locator_test.js +++ b/test/unit/locator_test.js @@ -306,6 +306,12 @@ describe('Locator', () => { expect(nodes).to.have.length(1); }); + it('should build locator to match element by class', () => { + const l = Locator.build('div').withClassAttr('form-'); + const nodes = xpath.select(l.toXPath(), doc); + expect(nodes).to.have.length(9); + }); + it('should build locator to match element containing a text', () => { const l = Locator.build('span').withText('Hey'); const nodes = xpath.select(l.toXPath(), doc);