Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Clean way to fill multiple inputs with puppeteer

When using puppeteer I use page.type() and I’ve noticed that when working with more than one input field the code begins to repeat itself.

Here is the shortened version of what I’m doing:

        await page.type('#idFirstName', user.first_name);
        await page.type('#idEmailAddress', user.email);
        await page.type('#idLastName', user.last_name);
        await page.type('#idCity', user.city);

Is there any way to fill multiple input fields without repeating the await page.type()?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Whenever you find yourself repeating the same syntax, it’s usually an indicator that you can use a loop.

In your example code, you repeatedly invoke the Page.type method, whose signature looks like this:

class Page {
  type(
    selector: string,
    text: string,
    options?: { delay: number }
  ): Promise<void>;
}

You appear to be supplying arguments for the first two parameters (selector and text), so you can create an array of tuples which represent those arguments, and then use a for...of loop to iterate over that array, supplying the arguments each time:

const argumentsList = [
  ['#idFirstName', user.first_name],
  ['#idEmailAddress', user.email],
  ['#idLastName', user.last_name],
  ['#idCity', user.city],
];

for (const [selector, text] of argumentsList) {
  await page.type(selector, text);
}

You can also spread the arguments when invoking the function instead of destructuring them:

for (const args of argumentsList) await page.type(...args);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading