Search code examples
javascriptnode.jspuppeteercodeceptjs

CodeceptJS / Puppeteer doesn't recognize 'if' statement


not really familiar with js/node.js. using codeceptjs/puppeteer for some automated tests. right now trying to edit a description in a test. but sometimes a description isn't there - therefor the 'edit description' button is not there - and there is a 'add description' button instead. so I wrote an if statement that specifies . but the code just rolls over it. it does not matter what the statement is, it just moves to the next line. currently if (desc) and if(!desc) both perform the same function - it goes to the next line in the if statement. this causes an error because there is a description already and therefor the 'add description' button is not available. I'm not sure what's going on.

Scenario('test something', (I, userLoginPage, FBPagePage) => {


    userLoginPage.validate();


    I.click('//*[@id="card_611"]');
       // clicks the card

    var desc = '//*[@id="show_card_description"]/section/button';
    // add description button
    // tried 'Add description' but the result was the same

    if (desc){
     // this is where the error happens. it simply looks for the add description button
     // no matter what button is there it decides to click the 'add description' button

        I.click('//*[@id="show_card_description"]/section/button');
    // click add desc button

        I.fillField('//*[@id="description_editor_container"]/div[2]/div[1]',
        'not admin user created this description thanks to automated testing');
    // types this stuff 
        I.click('//*[@id="description_editor_container"]/button[1]');
    // saves it 
        I.wait(1);
}

    I.click('//*[@id="show_card_description"]/section/h5/a');
    // click edit desc button if a description already exists
    I.fillField('//*[@id="description_editor_container"]/div[2]/div[1]', 'not admin user edited this description thanks to automated testing');
    I.click('//*[@id="description_editor_container"]/button[1]');


I.say('success!')
});

Solution

  • To give you the right context: You are asking a Node.js question, not CodeceptJS or Puppeteer at first place.

    desc is always true because you declare it as a string, so no matter what the code inside the if will run, as you already found out.

    You can use do something like:

    const numOfElements = await I.grabNumberOfVisibleElements('#show_card_description section button'); // Use CSS locator instead of Xpath for easier readability
    
    console.log(numOfElements); // Debug
    
    if(numOfElements === 1) {
       …
    }
    

    See also https://codecept.io/helpers/Puppeteer#grabnumberofvisibleelements