How to share a single Puppeteer instance across multiple Jest test files?

Stuck with Puppeteer and Jest setup

I’m trying to switch from CasperJS to Jest and Puppeteer for my tests. Everything works fine when I put all my tests in one file. But I want to split them into separate files for better organization.

The problem is I don’t want to create a new Puppeteer instance for each test file. It takes too long. I want to set up Puppeteer once and use it for all my tests.

I looked at Jest’s setupFiles option but it runs before every test file. That’s not what I want.

I also thought about creating a main file that imports and runs all the tests:

// set up Puppeteer
await import('./testA.js')(page, browser, config);
await import('./testB.js')(page, browser, config);
// clean up

This works but I can’t run tests separately anymore.

I’m new to Jest so I’m probably missing something obvious. Any ideas on how to share a Puppeteer instance across test files without setting it up multiple times?

hey luke, have u tried using jest’s globalSetup and globalTeardown? they run once for all tests. u can launch puppeteer in globalSetup, save the browser to a global var, and use it in ur tests. just remember to close it in globalTeardown. its way faster than making new browsers for each file. good luck!

I’ve been in a similar situation and found that creating a custom Jest environment was the key to sharing a Puppeteer instance across files. I started by making a file called puppeteer-environment.js where I set up the Puppeteer browser in the setup method and attached it to this.global. I ensured the browser was properly closed in the teardown phase. In my Jest configuration, I specified this custom environment so that every test file gets its own page instance while still sharing a single browser instance. This method required some trial and error, but it has improved performance considerably.

Having faced similar challenges, I’d suggest exploring Jest’s globalSetup and globalTeardown options. These run once before and after all test files, making them ideal for managing a shared Puppeteer instance. Create a setup file that launches the browser and stores it in a global variable. In your test files, access this global browser instance to create new pages as needed. Remember to close the browser in the teardown file. This approach maintains test isolation while significantly reducing setup time across your test suite. It’s worth noting that this method requires careful management of the global state, but it’s generally more efficient than reinitializing Puppeteer for each test file.