Jn Neer
Jn Neer

Reputation: 245

How to fetch all options of dropdown values in TestCafe

I have one dropdown which has n options values. How can I fetch all these options values and then assert them in one go in Test Cafe. I did not find anything in Documentation. Please let me now how can I do this.

Assume I have below dropdown :

<select id="city">
    <option>New York</option>
    <option>London</option>
    <option>Paris</option>
</select>

Upvotes: 1

Views: 2059

Answers (2)

Helen Dikareva
Helen Dikareva

Reputation: 1036

You can find a similar example in TestCafe Documentation (and we're going to provide a more extended one in the near future). In your case you can use the following code:

import { ClientFunction } from 'testcafe';

fixture `Get option values`
    .page `https://example.com`;

const getOptionNames = ClientFunction(() => {
    const select  = document.querySelector('#city');
    const options = select.querySelectorAll('option');
    const values  = [];

    for (let option of options)
        values.push(option.textContent);

    return values;
});

test('test', async t => {
    await t.expect(getOptionNames()).eql(['New York', 'London', 'Paris']);
});

Upvotes: 4

TallKU
TallKU

Reputation: 179

This solution is assuming that on your page there is no other option html items. That they are all underneath <select id="city"

test('TestCafe - Verify all Options', async (t) => {
    const optionList = Selector('option');
    for( var i = 0; i < await optionList.count; i++){
        const optionText = await optionList.nth(i).innerText;
        // Perform some validation/comparision on the text to see if it is as you expect....
    }
})

Upvotes: 3

Related Questions