Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to enable parallel tests with puppeteer?

Tags:

puppeteer

I am using the chrome puppeteer library directly to run browser integration tests. I have a few tests written now in individual files. Is there a way run them in parallel? What is the best way to achieve this?

like image 820
Matt Avatar asked Oct 06 '17 02:10

Matt


People also ask

Does puppeteer support parallel execution?

Parallel Testing means you can run multiple tests simultaneously, with Puppeteer. It allows you to speed up your test execution, drastically shortening your total test duration time.

What is parallel Testing?

Parallel testing is testing multiple applications or components of the application concurrently, to reduce the test time. Parallel tests consist of two or more parts that check separate parts or features of an application. These parts are executed on individual computers simultaneously.

Can I run puppeteer in browser?

Puppeteer is a Node.js library which provides a high-level API to control Chrome/Chromium over the DevTools Protocol. Puppeteer runs in headless mode by default, but can be configured to run in full (non-headless) Chrome/Chromium.


1 Answers

To run puppeteer instances in parallel you can check out this library I wrote: puppeteer-cluster

It helps to run different puppeteer tasks in parallel in multiple browsers, contexts or pages and takes care of errors and browser crashes. Here is a minimal example:

const { Cluster } = require('puppeteer-cluster');

(async () => {
  const cluster = await Cluster.launch({
    concurrency: Cluster.CONCURRENCY_CONTEXT, // use one browser per worker
    maxConcurrency: 4, // cluster with four workers
  });

  // Define a task to be executed for your data
  cluster.task(async ({ page, data: url }) => {
    await page.goto(url);
    const screen = await page.screenshot();
    // ...
  });

  // Queue URLs
  cluster.queue('http://www.google.com/');
  cluster.queue('http://www.wikipedia.org/');
  // ...

  // Wait for cluster to idle and close it
  await cluster.idle();
  await cluster.close();
})();

You can also queue your functions directly like this:

  const cluster = await Cluster.launch(...);

  cluster.queue(async ({ page }) => {
    await page.goto('http://www.wikipedia.org');
    await page.screenshot({path: 'wikipedia.png'});
  });

  cluster.queue(async ({ page }) => {
    await page.goto('https://www.google.com/');
    const pageTitle = await page.evaluate(() => document.title);
    // ...
  });

  cluster.queue(async ({ page }) => {
    await page.goto('https://www.example.com/');
    // ...
  });
like image 121
Thomas Dondorf Avatar answered Oct 17 '22 00:10

Thomas Dondorf