Andrew Wa
Andrew Wa

Reputation: 1

Is there a way to store elements on a page into an array from the Selector function in Testcafe?

I am new to testcafe, I have heard that there is a way to do this in Selenium, but I have not used that before either. I have tried storing buttons on a webpage into an array, but it seems like the buttons are not accessible when I try to test if the buttons are able to be accessed within the array.

// For the purposes of this example, let's say there are 2 buttons on the page,
// first one has the label "First" and the second has the label "Second".

test('sample', async t => {
    const numElements = Selector('button').filterVisible().count;
    const elements = [];
    for (let i = 0; i < numElements; i++) {
      elements.push(getButtonIndex(i));
    }
    await t.expect(Selector('button').withText('Second')).eql(elements[1]);
});

getButtonIndex(index) {
    return Selector('button').filterVisible().nth(index);
};

Is it possible to store HTML elements into an array with Selector? Or is there another way to do this?

I know it is possible to store individual attributes like the aria-label into an array, but if I had the same aria-label for 2 input elements as an example, how would I access the second one? As far as I know, the nth function in testcafe doesn't seem to work for this scenario.

Upvotes: 0

Views: 404

Answers (2)

Ilya Afanasenko
Ilya Afanasenko

Reputation: 527

Selectors can be stored in an array - there is no problem with that. The problem is that you have an error in the code above:

const numElements = Selector('button').filterVisible().count;

Add await:

const numElements = await Selector('button').filterVisible().count;

Upvotes: 1

Ilya Afanasenko
Ilya Afanasenko

Reputation: 527

In this case, the problem is not related to the nth function - it works properly. The fact is that in the context in which tests are executed, Selector('button').withText('Second') and Selector('button').filterVisible().nth(1) are different objects even if they point to the same HTML element. Try this comparison:

await t.expect(Selector('button').withText('Second').style).eql(elements[1].style);

Upvotes: 1

Related Questions