Skip to content

Extend locators with absAt(position) #1670

@nitschSB

Description

@nitschSB

What are you trying to achieve?

I want to do something with the first element that matches the locator.

What do you get instead?

I get an array of all matches.

I.amOnPage('https://www.google.com/search?q=test')
I.grabTextFrom(locate(h3).first())

Possible Solution

Extend the LocatorAPI (e.g. veryFirst() or absFirst())

  absAt(position) {
    if (position < 0) {
      position++; // -1 points to the last element
      position = `last()-${Math.abs(position)}`;
    }
    if (position === 0) {
      throw new Error('0 is not valid element position. XPath expects first element to have index 1');
    }
    // Important difference brackets around the first %s
    const xpath = sprintf('(%s)[position()=%s]', this.toXPath(), position);
    return new Locator({ xpath });
  }

  absFirst() {
    return this.absAt(1);
  }

  absLast() {
    return this.absAt(-1);
  }

Details

  • CodeceptJS version: 2.1.1
  • NodeJS Version: does not matter
  • Operating System: does not matter
  • puppeteer: 1.11.0
  • Configuration file: does not matter

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions