testing-library / pptr-testing-library

puppeteer + dom-testing-library = 💖
MIT License
287 stars 29 forks source link

Support waitForElementToBeRemoved #45

Open umpox opened 4 years ago

umpox commented 4 years ago

waitFor and find* queries are supported but waitForElementToBeRemoved is not currently. It would be useful to add this async util to avoid having to write boilerplate code around waitFor and expect

waitForElementToBeRemoved - DOM Testing Library

avimar commented 3 years ago

waitForElementToBeRemoved seems to pass in a selector. I'm needing to wait for an actual element to be removed. (I have a "continue" button on each stage of a form, and because of a transition, there's a moment that you can see both "continue" buttons.)

Apparently, you can check if the elementHandle is still connected with await elementHandle.evaluate(el => el.isConnected) https://github.com/puppeteer/puppeteer/issues/640#issuecomment-510703934

avimar commented 3 years ago

Here's my generic function that you can include under the MIT license to wait for an actual elementHandle to be removed. I didn't write the sleep function... it should be generic enough, though...

This code seems to work as a generic function:

function sleep(ms) {
    return new Promise((resolve) => {
        setTimeout(resolve, ms);
        });
    }
async function waitForElementHandleToBeRemoved(elementHandle,waitMax=5000,waitStep=100){
    const timeStart = new Date().valueOf();
    var elementVisible = true;
    var timeNow=timeStart;
    while((timeNow-timeStart)<waitMax && elementVisible){
        await sleep(waitStep);
        elementVisible = await elementHandle.evaluate(el => el.isConnected);
        timeNow = new Date().valueOf();
        }
    if(!elementVisible) return true;
    throw new Error('element still visible after '+waitMax+'ms');
    }