How to use $$[n] in Spectron/WebdriverIO to target the nth child element instead of the selector

Attempting to utilize Spectron for testing my Electron application has been challenging. According to the documentation, in order to locate the nth child element, you can either use an nth-child selector or retrieve all children that match a selector using $$, followed by utilizing the index operator as shown in $$ ("foo")[0] to access the first occurrence of "foo." VIEW DOCS

Assuming this information, I anticipate the following code snippet to display: BAR However, my attempts to achieve this have been unsuccessful:

const foo = ".foo";
const fooElements = app.client.$$ (foo);
console.log ("FOOELEMENTS", await TP (app.client.getHTML (foo)));
console.log ("BAR", fooElements[0].getText (".bar"));

This results in the following output:

console.log components\pages\analysis\__test__\Analysis.spectron.ts:44
    FOOELEMENTS [ '<div class="foo"><div class="bar">BAR</div><div class="baz">BAZ</div></div>',
    '<div class="foo"><div class="bar">BAR2</div><div class="baz">BAZ2</div></div>',
    '<div class="foo"><div class="bar">BAR3</div><div class="baz">BAZ3</div></div>'
    '<div class="foo"><div class="bar">BAR4</div><div class="baz">BAZ4</div></div>' ]

console.log components\pages\analysis\__test__\Analysis.spectron.ts:50
    EXCEPTION TypeError: Cannot read property 'getText' of undefined
        at components\pages\analysis\__test__\Analysis.spectron.ts:45:44
        at Generator.next (<anonymous>)
        at fulfilled (components\pages\analysis\__test__\Analysis.spectron.ts:4:58)
        at <anonymous>
        at process._tickDomainCallback (internal/process/next_tick.js:228:7)

In the HTML output, there are indeed multiple .foo divs present. However, when attempting to access the first one using fooElements[0], it returns undefined.

A side note (although seemingly irrelevant): TP functions as an alias I created for a custom function named toPromise, enabling me to efficiently await the webdriver promises due to TypeScript's confusion with their implementation:

export async function toPromise<T> (client: Webdriver.Client<T>)
{
    return client as any as Promise<T>;
}

// Promise
    interface Client<T> {
        finally(callback: (...args: any[]) => void): Client<T>;

        then<P>(
            onFulfilled?: (value: T) => P | Client<P>,
            onRejected?: (error: any) => P | Client<P>
        ): Client<P>;

        catch<P>(
            onRejected?: (error: any) => P | Client<P>
        ): Client<P>;

        inspect(): {
            state: "fulfilled" | "rejected" | "pending";
            value?: T;
            reason?: any;
        };
    }

Any insights into where I might be going wrong? Or perhaps an alternative approach you could recommend? I would prefer to steer clear of nth-child selectors if possible.

EDIT: Updated to use classes instead of IDs

Answer №1

When using webdriver, the window index and elements are actually referenced to as the first element.

I personally found this approach to work well for me.

var button = ('//*[contains(@class,"popper")]')[1];

return this.app.client.click(button);

For example:

class Clix {

    constructor() {

        this.clix_search = '(//input[contains(@class,"clix-search")])[1]';

    }

    clix_input_search(app) {
        return help.setValue(app, this.clix_search, "pack");
    }

}

Within the helpers class:

setValue(app, element, text) {

        return app.client.waitForVisible(element, 60000)
            .waitForEnabled(element, 60000)
            .clearElement(element)
            .setValue(element, text)
            .getValue(element)
            .should.eventually.equal(text)

    }

Answer №2

Initially, your example is quite interesting. I am curious about how you managed to get that specific piece of <html> code to run successfully. It's important to note that the value of the id attribute must be unique:

The id attribute specifies a unique id for an HTML element (the value must be unique within the HTML document).

To make your code work correctly, all you need to do is remove the #bar selector. You were passing the selector information to the ELEMENT object when it was already contained in the value of the selector key.

let locator = 'span[connectqa-device="installed"]'

browser.debug()

Resulting output (test blocked in debug-mode):

> let elems = $$(locator)
[18:10:22]  COMMAND     POST     "/wd/hub/session/775b024e-0b6a-4a60-a5b2-26d4df961d0a/elements"
[18:10:22]  DATA                {"using":"css selector","value":"span[connectqa-device=\"installed\"]"}
[18:10:22]  RESULT              [{"element-6066-11e4-a52e-4f735466cecf":"c6719646-30da-43ff-9b17-40c074b4988a"},{"element-6066-11e4-a52e-4f735466cecf":"d5f8acf2-8f4f-4554-9fe6-7f863555f5b5"},{"element-6066-11e4-a52e-4f735466cecf":"53ff9b0a-2a88-4b13-9e54-9c54411c03c5"}]

> elems[0]
{ ELEMENT: 'c6719646-30da-43ff-9b17-40c074b4988a',
  'element-6066-11e4-a52e-4f735466cecf': 'c6719646-30da-43ff-9b17-40c074b4988a',
  selector: 'span[connectqa-device="installed"]',
  value: { ELEMENT: 'c6719646-30da-43ff-9b17-40c074b4988a' },
  index: 0 }
>
> elems[0].selector
'span[connectqa-device="installed"]'
>
> elems[0].getText()
[18:10:54]  COMMAND     GET      "/wd/hub/session/775b024e-0b6a-4a60-a5b2-26d4df961d0a/element/c6719646-30da-43ff-9b17-40c074b4988a/text"
[18:10:54]  DATA                {}
[18:10:54]  RESULT              "Installed"
'Installed'

In another approach, you could have used this instead:

let retText2 = browser.getText('span[connectqa-device="installed"]')
or
> let retText2 = browser.getText(elems[0].selector)
. However, the second method is purely for educational purposes, as it might not be the ideal way to accomplish the task in practice.

I hope this explanation proves helpful. Best regards!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible to implement a redirect in Angular's Resolve Navigation Guard when an error is encountered from a resolved promise?

I have integrated Angularfire into my Angular project and am utilizing the authentication feature. Everything is functioning properly, however, my Resolve Navigation Guard is preventing the activation of the component in case of an error during the resolve ...

Subcomponent in React is not rendering as expected

I have a primary React component with a subcomponent named AttributeInput. To prevent redundancy in my code, I moved some of the logic from the main component to a method within AttributeInput. My attempt at referencing this code looks like this: {this.s ...

Exploring the TypeScript compiler API to read and make updates to objects is an interesting

I'm delving into the world of the typescript compiler API and it seems like there's something I am overlooking. I am trying to find a way to update a specific object in a .ts file using the compiler API. Current file - some-constant.ts export co ...

Unable to close Bootstrap modal upon clicking "x" or "close" buttons

Hey everyone, I'm having a bit of trouble with my modal. It appears correctly when clicked to open, and the close buttons seem to detect that my mouse is hovering over them. However, when I click on the buttons, nothing happens and the modal remains o ...

Having trouble using Node-fetch with Electron 11? Keep getting an error message that says resp.body.pipe is not a function

Currently, I am attempting to utilize node-fetch in order to download a zip file from a specific URL. However, I keep encountering this error message: TypeError: res.body.pipe is not a function After upgrading my Electron app version from "electron&q ...

The functionality of a website's design acts as a safeguard against unauthorized data transfers

I am encountering a major issue with my website. The layout I have created seems to be hindering me from making any modifications. My website consists of several containers, with three small containers stacked on top of each other as the main section of ...

The data displayed in the <span> element isn't reflecting the response from the loaded page, despite being visible in Firebug

I have encountered a problem while trying to load a signup.php page into a div on my main page. All the elements (forms, JavaScript, etc.) function correctly in the loaded page, except for one issue - I cannot get the response from the PHP script to displa ...

Retrieving the link to share for every video located in the Dropbox folder

My Dropbox folder contains a set of videos labeled "v1.avi, v2.avi, ....., vn.avi". I am looking to automate the process of extracting the share link for each video in the folder so that I can easily use it as a source value for HTML video. . . . Is ther ...

How can a JQuery slideshow be programmed to only iterate once?

Looking to create a slideshow that transitions between images every two seconds? Check out the code snippet below: HTML: <div class="fadeIn"> <img src="img/city.png" class="remimg" id="city"> <img src="img/shop.png" class="remimg" ...

Strip away double quotation marks from object attributes except those beginning with a number

I've searched extensively and reviewed various Q&A forums, but I haven't encountered a scenario quite like this. Here's an example of the object I'm working with: props: { "label": "1rem", "text3": "1rem", "text2Button": "1re ...

Retrieve the unique identifier of a div using JavaScript/jQuery

I am faced with a situation where I have two sets of divs structured as follows: First Div <div class="carousel"> <div class="item active" id="ZS125-48A">...</div> <div class="item" id="FFKG-34">...</div> <div cl ...

What is the best way to create a distinct key for the key prop in my map function within a React component?

This is the initial code I have: class Board extends Component { static defaultProps = { nrows: 5, ncols: 5, chanceLightStartsOn: 0.25 }; constructor(props) { super(props); this.state = { hasWon: false, board: this. ...

What is the best way to test a local variable in Angular 2 using karma and jasmine?

I've been working on writing a unit test with jasmine, but I've run into an issue when trying to test a local variable using jasmine. I have successfully tested a global variable in the past, but testing a local variable seems to be more challeng ...

The Nuxt content Type 'ParsedContent | null' cannot be assigned to type 'Record<string, any> | undefined'

I've been experimenting with @nuxt/content but I'm struggling to create a functional demo using a basic example. ERROR(vue-tsc) Type 'ParsedContent | null' is not assignable to type 'Record<string, any> | undefined'. ...

Downloading a file utilizing Selenium through the window.open method

I am having trouble extracting data from a webpage that triggers a new window to open when a link is clicked, resulting in an immediate download of a csv file. The URL format is a challenge as it involves complex javascript functions called via the onClick ...

Responsive design element order rearrangement

My code example is as follows: <div class="info-container"> <span class="item1">item1</span> <a class="item2" href="#">item2</a> <a class="item3" href="#">item3</a> </div> I want to rearran ...

how to use AngularJS filter and ng-options to format specific options as bold in a select dropdown

I am currently utilizing AngularJS ng-options to populate specific select elements. I am interested in bolding and disabling certain options. Despite trying to achieve this using the filter along with ng-options, I have been unsuccessful so far. While I ca ...

The integration of Zoom SDK with React and Node inevitably leads to encountering errors

I have been struggling to integrate zoomsdk into my react app and have followed all the steps mentioned here. The backend part is functioning properly, and I am receiving the signature response. However, when attempting to run the frontend portion, I encou ...

Ensure that react-native-google-places-autocomplete is assigned a specific value rather than relying on the default value

I am currently using a functional <TextInput>: <TextInput placeholder="Location" value={props.locationInput.toString()} onChangeText={location => props.updateLocationInput(location)} /> Initially, the props.locationIn ...

validation for grouped radio inputs

I'm having a small issue with appending error states. I have 7 radio inputs and after submitting, I see 7 error states under the group. Can someone assist me in modifying the code? <form class="register-form"> <div class="co ...