Testare le estensioni di Chrome con Puppeteer

Puppeteer fornisce un framework per la creazione di test automatici di siti web, che include anche la possibilità di testare le estensioni di Chrome. Si tratta di test end-to-end di alto livello che testano la funzionalità di un sito web o di un'estensione una volta integrati nel prodotto finale. In questo tutorial, mostriamo come scrivere un test di base per un'estensione dal nostro repository di esempi.

Prima di iniziare

Clona o scarica il repository chrome-extensions-samples. Utilizzeremo la demo dell'API History in api-samples/history/showHistory come estensione di test.

Dovrai anche installare Node.JS, il runtime su cui è basato Puppeteer.

Scrivere il test

Passaggio 1: avvia il progetto Node.js

Dobbiamo configurare un progetto Node.JS di base. In una nuova cartella, crea un file package.json con il seguente contenuto:

package.json:

{
  "name": "puppeteer-demo",
  "version": "1.0"
}

Analogamente al file manifest.json di un'estensione, questo file è richiesto da tutti i progetti Node.

Passaggio 2: installa Puppeteer e Jest

Esegui npm install puppeteer jest per aggiungere Puppeteer e Jest come dipendenze. Verranno aggiunti automaticamente al file package.json.

È possibile scrivere test Puppeteer autonomi, ma utilizzeremo Jest come test runner per fornire una struttura aggiuntiva al nostro codice.

Passaggio 3: crea un punto di ingresso

Crea un nuovo file denominato index.test.js e aggiungi il seguente codice:

index.test.js:

const puppeteer = require('puppeteer');

const EXTENSION_PATH = '../../api-samples/history/showHistory';

let browser;
let worker;

beforeEach(async () => {
  // TODO: Launch the browser.
});

afterEach(async () => {
  // TODO: Close the browser.
});

Passaggio 4: avvia il browser

Aggiorna beforeEach e afterEach per avviare e chiudere il browser. Quando esegui molti test, ti consigliamo di utilizzare lo stesso browser. Tuttavia, questa operazione è generalmente sconsigliata perché riduce l'isolamento tra i test e potrebbe far sì che un test influisca sul risultato di un altro.

index.test.js:

beforeEach(async () => {
  browser = await puppeteer.launch({
    headless: false,
    pipe: true,
    enableExtensions: [EXTENSION_PATH]
  });
});

afterEach(async () => {
  await browser.close();
  browser = undefined;
});

Passaggio 5: attendi il service worker dell'estensione

Dobbiamo attendere l'avvio del service worker dell'estensione per poterlo utilizzare in un secondo momento per aprire il popup. Aggiorna la funzione beforeEach con il seguente codice:

beforeEach(async () => {
  browser = await puppeteer.launch({
    headless: false,
    pipe: true,
    enableExtensions: [EXTENSION_PATH]
  });

  const workerTarget = await browser.waitForTarget(
    // Assumes that there is only one service worker created by the extension
    // and its URL ends with service-worker.js.
    (target) =>
      target.type() === 'service_worker' &&
      target.url().endsWith('service-worker.js')
  );

  worker = await workerTarget.worker();
});

Passaggio 6: aggiungi un alias

Per semplificare l'esecuzione dei test, aggiungi un alias al file package.json:

package.json:

{
  "name": "puppeteer-demo",
  "version": "1.0",
  "dependencies": {
    "puppeteer": "^24.8.1"
  },
  "scripts": {
    "start": "jest ."
  }
}

Verranno eseguiti tutti i file che terminano con .test.js nella directory corrente.

Passaggio 7: apri il popup

Aggiungi un test di base. Per prima cosa, apriamo una nuova pagina in modo che ci sia un elemento nella cronologia del browser. Poi, si aprirà il popup per visualizzare i contenuti della cronologia. Aggiungi il seguente codice:

index.test.js:

test('popup renders correctly', async () => {
  // Open a page to add a history item.
  const page = await browser.newPage();
  await page.goto('https://example.com');

  // Open the extension popup.
  await worker.evaluate('chrome.action.openPopup();');

  const popupTarget = await browser.waitForTarget(
    // Assumes that there is only one page with the URL ending with popup.html
    // and that is the popup created by the extension.
    (target) => target.type() === 'page' && target.url().endsWith('popup.html')
  );
});

Passaggio 8: verifica lo stato attuale

Afferma qualcosa, in modo che il test possa non riuscire se l'estensione non si comporta come previsto. Sappiamo che il nostro popup dovrebbe mostrare le pagine visitate di recente, quindi controlla che ne venga visualizzata una:

index.test.js:

test('popup renders correctly', async () => {
  // Open a page to add a history item.
  const page = await browser.newPage();
  await page.goto('https://example.com');

  // Open the extension popup.
  await worker.evaluate('chrome.action.openPopup();');

  const popupTarget = await browser.waitForTarget(
    // Assumes that there is only one page with the URL ending with popup.html
    // and that is the popup created by the extension.
    (target) => target.type() === 'page' && target.url().endsWith('popup.html')
  );

  const popup = await popupTarget.asPage();

  const list = await page.$('ul');
  const children = await list.$$('li');

  expect(children.length).toBe(1);
});

Passaggio 9: esegui il test

Per eseguire il test, utilizza npm start. Dovresti vedere un output che indica che il test è stato superato.

Puoi visualizzare il progetto completo nel nostro repository chrome-extensions-samples.

Passaggi successivi

Dopo aver acquisito le nozioni di base, prova a creare una suite di test per la tua estensione. Il riferimento API di Puppeteer contiene ulteriori informazioni su ciò che è possibile fare. Esistono molte funzionalità non descritte qui.