DEV Community

Cover image for How to wait for animations to complete in Playwright script
Sergey Todyshev
Sergey Todyshev

Posted on

1 1

How to wait for animations to complete in Playwright script

In this post I am going to show a function to wait for animations to complete in Playwright test script.
As usual enough words, just try to apply the code below πŸ˜„

async function waitNoMutations(page, selector) {
  return await page.evaluateHandle(function (selector) {
    var list = document.querySelectorAll(selector);
    var elements = [].slice.call(list);
    var config = { attributes: true, childList: true, subtree: true };
    var mutations = 5; // wait at least five intervals

    var observer = new MutationObserver(function () {
      mutations += 1;
    });
    elements.forEach(function (target) {
      observer.observe(target, config);
    });

    var decrementInterval = setInterval(function () {
      mutations -= 1;
      if (mutations <= 0) {
        clearInterval(decrementInterval);
      }
    }, 5); // this quant might be reduced?

    function complete() {
      return mutations <= 0;
    }

    return new Promise(function (resolve) {
      var count = 0;
      var completeInterval = setInterval(function () {
        if (count >= 1000) { // timeout?
          clearInterval(completeInterval);
          observer.disconnect();
          resolve("timeout");
          return;
        }
        if (complete()) {
          clearInterval(completeInterval);
          observer.disconnect();
          resolve(true);
          return;
        }
        count += 1;
      }, 5);
    });
  }, selector);
}
Enter fullscreen mode Exit fullscreen mode

This works, but not in 100% cases πŸ˜„

Enjoy! EOF πŸ˜„

Link to original post.

Top comments (0)

SurveyJS custom survey software

Build Your Own Forms without Manual Coding

SurveyJS UI libraries let you build a JSON-based form management system that integrates with any backend, giving you full control over your data with no user limits. Includes support for custom question types, skip logic, an integrated CSS editor, PDF export, real-time analytics, and more.

Learn more

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay