Search code examples
javascriptautomated-testse2e-testingweb-testingtestcafe

Testcafe find element


I did my first basic automated tests with TestCafe.

import { Selector } from 'testcafe';

fixture `Ordner erstellen`
    .page `https://ifoerster.com/`;

test('New Test', async t => {
    await t
        .typeText(Selector('#email'), 'xxx', {
            caretPos: 0
        })
        .typeText(Selector('#password'), 'xxx', {
            caretPos: 0
        })
        .click(Selector('span').withText('Login'))

        //Find testref here
        .click(Selector('.np-top-section-tab.folder'))
        .click(Selector('.np-folder.new-category'))
        .typeText(Selector('[class^="ReactModal__Content ReactModal__Content--after-ope"]').find('.cl-input.cl-input-header'), 'testref')
        .click(Selector('.cl-button.cl-button.cl-button-animated'))
        .click(Selector('.np-folder-name[title="testref"]'))
        .click(Selector('.np-bottom-path-section').find('span').withText('Home'))
        .click(Selector('div').withText('testref').nth(9).find('.np-folder-fave'))
        .click(Selector('span').withText('testref'))
        .click(Selector('.cl-folder-delete'))
        .click(Selector('.cl-button.cl-button.cl-button-animated'))
        .click(Selector('.cl-popup-close'));
});

Now I try to find the element

.click(Selector('.np-folder-name[title="testref"]'))

at the position //Find testref here. If/Once found, I do not want to execute the new category steps after //Find testref here.

My question is, how I can find an element on the webpage and can I add an if function as a step to ignore steps when an element is found? Like an if function or similar?


Solution

  • Use conditional logic in this case:

    await t
            .typeText(Selector('#email'), 'xxx', {
                caretPos: 0
            })
            .typeText(Selector('#password'), 'xxx', {
                caretPos: 0
            })
            .click(Selector('span').withText('Login'))
    
            const testFefElement = Selector('.np-folder-name[title="testref"]');
    
            if (await testFefElement.exists) {
                // condition is true
            }
            else {
                // condition is false
            }