javascripttestcafe

TestCafe equivalent of document.querySelectorAll()


I want to do the equivalent of this

document.querySelectorAll('.my-class').forEach(element => element.click())

in TestCafe. I.e. selecting multiple elements with a specific class and clicking on all of them. And I don't know how many elements there are in advance, so I can't use any hardcoded solution.

I've tried

test('My Test', async (t) => {
    const boxes = Selector('.my-class')

    const count = boxes.length // attempt 1
    // const count = boxes.count // attempt 2
    // const count = await boxes.count // attempt 3

    for (let i = 0; i < count; i++) {
        await t.click(boxes.nth(i))
    }
})

but no luck.

I've tried googling, looking at TestCafe's API, and asking ChatGPT but I can't seem to find anything regarding selecting multiple elements that share the same selector.


Solution

  • Actually it turned out that attempt 3 did, in fact, work... I had just mistakenly used the wrong selector string.

    So this works:

    test('My Test', async (t) => {
        const boxes = Selector('.my-CORRECT-class')
    
        const count = await boxes.count
    
        for (let i = 0; i < count; i++) {
            await t.click(boxes.nth(i))
        }
    })
    

    The .count property is a promise so that's why you have to await it (even if you were to await Selector).