Playwright: how to ensure an element does NOT exist?

Viewed 58

I'm trying to use Playwright with Jest to automate some test about uploading a file in a Microsoft Teams channel.

This is what I have and works:

it('should upload a file', async () => {
    // Listen to file chooser popup and set file for upload
    page.on('filechooser', async (fileChooser) => {
        await fileChooser.setFiles('test-files/example.txt');
    });

    // wait for the content iframe to be loaded
    const contentFrame = page.frameLocator('[name="embedded-page-container"]');

    // @TODO here I would like to first make sure the file does not exist
    // 
    // How could I do that ???
    // 

    // upload file and check for existence in file list displayed
    await contentFrame.locator('button[name="Upload"]').click();
    await contentFrame.locator('button[name="Files"]').click();
    await contentFrame.locator('button:has-text("example.txt")').waitFor({ state: "visible" });
});

The question: How could I check that the file does not exist before ?
Basically how do I check that the button:has-text("example.txt") element which I wait to become visible at the last line, does NOT exist before the upload action ?

Thanks.

1 Answers

I did something similar with python instead of javascript, but it should be useful for you.

I defined my own function in a helper:

def my_own_wait_for_selector(page, selector, time_out):
    try:
        page.wait_for_selector(selector, timeout=time_out)
        return True
    except:
        return False

Then you can use it for knowing if your element is in the DOM or not and take a decision/flow based on that

if helper.my_own_wait_for_selector(page, "MySelector", 5000):
    #Whatever I want to do if element is there
else:
    #Whatever I want to do if element is NOT there
Related