jeudi 11 mars 2021

How can I force one function through a set of conditionals in a separate function?

I'm working with puppeteer, and have written an async fn that takes screenshots of different pages. I loop through an array of widgets, append a code to the url, snap that page, and then move on. However, there are some exceptions I need to look out for on each page. e.g. if widget === "schedule-preview", I need to set the viewport to be a certain size. In some cases, I also need to click elements on the dom to expand various components. I can do that inline and it works just fine:

// set the url
await page.goto(buildUrl(widget, config, themeColor));

// check for various conditions
if (widget === "schedule-preview") {
  if (config.label === "Default") {
    page.setViewport({ width: 1920, height: 2160 });
    await page.waitForSelector(`[data-list-item-key="AAA"]`);
  } else if (config.label === "Complete") {
    page.setViewport({ width: 1920, height: 2160 });
    await page.waitForSelector(`[data-list-item-key="BBB"]`);
  } else {
    await page.waitForSelector(
      `[aria-label="*Expand⁩"]`
    );
    await page.click(`[aria-label="*Expand"]`);
    await page.waitForSelector(
      `[data-list-item-key="00000000"]`
    );
  }
}

// snap a screenshot
await page.screenshot({
  path: `${dir}/${themeColor}.jpeg`,
  fullPage: true,
});

However, I wanted to extract that logic into a separate fn to make the code a bit cleaner. I created a checkExceptions function, passed in the necessary data, and copied all of that conditional logic into it. But the main fn just continues as if the checkExceptions fn isn't even there.

How can I force my fn to go through those if checks, while also separating out concerns?

EDIT: The checkExceptions fn was literally just those conditionals you see there, wrapped in an async function block.

So, essentially:

async function checkExceptions(widget, config, page) {
// those exact conditionals from the example above
}

When I called checkExceptions in the main fn, I tried calling it normally (so just checkExceptions(widget, config, page)) and with an await.

Didn't explicitly return anything; tried returning individual await statements from inside the conditional blocks, but I'm not sure why I thought that would work because in some cases I need to return a click event and two waitForSelectors

Aucun commentaire:

Enregistrer un commentaire