Skip to content

Instantly share code, notes, and snippets.

@sdumetz
Last active August 21, 2024 13:55
Show Gist options
  • Save sdumetz/05c2674f978618f4f97caa105955e6d6 to your computer and use it in GitHub Desktop.
Save sdumetz/05c2674f978618f4f97caa105955e6d6 to your computer and use it in GitHub Desktop.
Use puppeteer with mocha --parallel while keeping just one browser instance
'use strict';
// Use puppeteer with mocha --parallel while keeping just one browser instance
// run with `mocha --require puppeteer_hooks.js`
// It uses puppetter's connect method to wire test suites to the browser
// See : https://github.com/puppeteer/puppeteer/blob/main/docs/api.md#puppeteerconnectoptions
//Access the browser in tests using `this.browser`
const fs = require('fs').promises;
const path = require('path');
const os = require('os');
const puppeteer = require('puppeteer');
const options = {
args:["--no-sandbox"]
};
const FILE = path.join(os.tmpdir(), 'mocha_puppeteer_wsEndpoint');
//Global browser
exports.mochaGlobalSetup = async function(){
this.browser = await puppeteer.launch();
await fs.writeFile(FILE, this.browser.wsEndpoint());
}
exports.mochaGlobalTeardown = async function(){
await this.browser.close();
await fs.unlink(FILE);
}
exports.mochaHooks = {
async beforeAll(){
const wsEndpoint = await fs.readFile(FILE, {encoding:"utf8"});
if (!wsEndpoint) {
throw new Error('Puppeteer\'s wsEndpoint not found');
}
this.browser = await puppeteer.connect({browserWSEndpoint:wsEndpoint});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment