megclaypool
3/7/2019 - 6:31 PM

Puppeteer and Jest -- Commands

[Puppeteer and Jest -- Commands]

Go to a URL

page.goto(WHATEVER_URL)

Wait for the page to load

await page.waitForNavigation({waitUntil: 'load'});

Get the current URL

page.url() or
let checkUrl = await page.evaluate(() => location.href);

Click on an element

page.click("ELEMENT_SELECTOR")

Type something

page.type("SELECTOR_OF_ELEMENT_TO_TYPE_IN", "THING_TO_TYPE_(NO_QUOTES_IF_VARIABLE)")

Check if an element is visible or hidden

page.waitForSelector(selector[, options])

  • selector A selector of an element to wait for
  • options Optional waiting parameters
    • visible wait for element to be present in DOM and to be visible, i.e. to not have display: none or visibility: hidden CSS properties. Defaults to false.
    • hidden wait for element to not be found in the DOM or to be hidden, i.e. have display: none or visibility: hidden CSS properties. Defaults to false.
    • timeout maximum time to wait for in milliseconds. Defaults to 30000 (30 seconds). Pass 0 to disable timeout. The default value can be changed by using the page.setDefaultTimeout(timeout) method.
  • returns: <Promise<?ElementHandle>> Promise which resolves when element specified by selector string is added to DOM. Resolves to null if waiting for hidden: true and selector is not found in DOM.

or

One method is by checking its display style value. Second is by checking its height, for exp if the element is a child of an element which is display: none, the offsetHeight will be 0 and thus you know the element is not visible despite its display value. opacity: 0 is not considered as hidden element so we will not checking it.

const isNotHidden = await page.$eval('#menu', (elem) => { return window.getComputedStyle(elem).getPropertyValue('display') !== 'none' && elem.offsetHeight });
You can check elem.offsetWidth as well and is not bad before any calculation, check if element exist or not.