Search code examples
testingautomated-testse2e-testingweb-testingtestcafe

Using document.getElementsByClassName in Testcafe


I have a menu that always has the same structure, but the IDs can change from one installation to another. the only thing that stays the same is the heading (in my case "Plugins"). I call the document.getElementsByClassName function with a Selector inside my test:

var slides = Selector(() =>{
    return document.getElementsByClassName("c-p-header-text");
});

Every heading of an menu element has the c-p-header-text class. Here is what a menu heading element looks like:

<div id="ext-comp-1002" class="c-p c-tree c-p-collapsed" style="width: auto;">
     <div class="c-p-header c-unselectable c-accordion-hd" id="ext-gen135" style="cursor: pointer;">
        <div class="c-tool c-tool-toggle" id="ext-gen140">&nbsp;</div>
        <img src="/backEnd/images/s.gif" class="c-p-inline-icon order"><span class="c-p-header-text" id="ext-gen150">Plugins</span>
     </div>

It would be easy to use await t.click("#ext-gen150") but it is not safe that it is always this id.

here is what i tried:

await t
    .click('#sites__db');
var slides = Selector(() =>{
    return document.getElementsByClassName("c-p-header-text");
});
console.log("[DEBUG]" + slides);
console.log("[DEBUG] found " + slides.length + " elements");
for(var i = 0; i < slides.length; i++)
{
    var txtOfCurrElem = slides.item(i).innerText; 
    console.log("[DEBUG "+ i +"] Text: " + txtOfCurrElem);
}

Running this test give me the following output:

[DEBUG]function __$$clientFunction$$() {
        var testRun = builder.getBoundTestRun() || _testRunTracker2.default.resolveContextTestRun();
        var callsite = (0, _getCallsite.getCallsiteForMethod)(builder.callsiteNames.execution);
        var args = [];

        // OPTIMIZATION: don't leak `arguments` object.
        for (var i = 0; i < arguments.length; i++) {
            args.push(arguments[i]);
        }return builder._executeCommand(args, testRun, callsite);
    }
[DEBUG] found 0 elements

The plan is to find the element (with the heading "Plugins") and then click on it when the test continuous.


Solution

  • I found a simple answer to my question. I use the .withText option to click on the Plugins element:

    .click(Selector('span').withText("Plugins"))
    

    Since this name is also unique, it is always the correct element that gets clicked. I do not know if it would have worked with the solution from @AndreyBelym if my site is not an extJS web application.