Search code examples
javascriptjquerynode.jsecmascript-6testcafe

How to write an if condition without waiting for checking if a selector does NOT exist with Node.js and TestCafe


Sorry for the total N00b question, but here goes,

I'm working on writing some test automation, and the website I'm automating sometimes has certain behaviors with certain elements on the page, and other times it has different behaviors with different elements on the page. It usually falls into one of two modes. Call it mode A & mode B. The thing is there is some shared elements between mode A & mode B, so it's not exclusively different elements.

However, in either case there is one element that is always on the screen when mode B is active, and it is not on the screen when mode A is active. Also mode A has a slightly longer workflow with a few extra controls to interact with. Lets call this one element "ProfileIdentifier". I've got a locator for it, and I'd like to write some logic code that checks if this element does not exist then interact with the extra controls and do the longer workflow, followed by the common controls and workflow that is common between mode A & mode B.

In short, something like this:

import mypage from '../../page-objects/mypage'; //JS file with all the locators for that page.

async function FillOutForm(t) {
    var profileIdentifier = t.getElement(mypage.profileIdentifierLocator);
    if (not(profileIdentifier.exists)) {
        // Do the extra workflow
    }
    // Do the common workflow
}

Or perhaps something like this:

import mypage from '../../page-objects/mypage'; //JS file with all the locators for that page.

async function FillOutForm(t) {
    var profileIdentifier = t.getElement(mypage.profileIdentifierLocator);
    if (profileIdentifier.exists.notOk()) {
        // Do the extra workflow
    }
    // Do the common workflow
}

NOTE: I've looked at other similar questions like: related question #1

I did see a glimmer of hope in one of the answers to this question: Possible answer

$('.myModal').isPresent().then(function(inDom) {
     return inDom; // returns bool
};

I'm using the Atom JavaScript editor, in combination with TestCafe and ES6 and I'd prefer to say away from code like getElementById, as this isn't the best (performant & stable) way to leverage CSS locators in JavaScript, especially if we have to re-use similar locators across other sections of our site for styling and other testing automation.


Solution

  • You can use the exists asynchronous property to check whether the element exists.

    import mypage from '../../page-objects/mypage'; //JS file with all the locators for that page.
    
    async function FillOutForm(t) {
        if (!await mypage.profileIdentifierLocator.exists) {
            // Do the extra workflow
        }
    
        // Do the common workflow
    }