With the Global Setup/Teardown and Async Test Environment APIs, Jest can work smoothly with puppeteer.

Generating code coverage for test files using Puppeteer is currently not possible if your test uses page.$eval, page.$$eval or page.evaluate as the passed function is executed outside of Jest's scope. Check out issue #7962 on GitHub for a workaround.

A jest-puppeteer example

The basic idea is to:

  • launch & file the websocket endpoint of puppeteer with Global Setup
  • connect to puppeteer from each Test Environment
  • close puppeteer with Global TeardownHere's an example of the GlobalSetup script
  1. // setup.js
  2. module.exports = async function() {
  3. const browser = await puppeteer.launch();
  4. // store the browser instance so we can teardown it later
  5. global.__BROWSER__ = browser;
  6. // file the wsEndpoint for TestEnvironments
  7. mkdirp.sync(DIR);
  8. fs.writeFileSync(path.join(DIR, 'wsEndpoint'), browser.wsEndpoint());
  9. };

Then we need a custom Test Environment for puppeteer

  1. // puppeteer_environment.js
  2. class PuppeteerEnvironment extends NodeEnvironment {
  3. constructor(config) {
  4. super(config);
  5. }
  6. async setup() {
  7. await super.setup();
  8. // get the wsEndpoint
  9. const wsEndpoint = fs.readFileSync(path.join(DIR, 'wsEndpoint'), 'utf8');
  10. if (!wsEndpoint) {
  11. throw new Error('wsEndpoint not found');
  12. }
  13. // connect to puppeteer
  14. this.global.__BROWSER__ = await puppeteer.connect({
  15. browserWSEndpoint: wsEndpoint,
  16. });
  17. }
  18. async teardown() {
  19. await super.teardown();
  20. }
  21. runScript(script) {
  22. return super.runScript(script);
  23. }
  24. }

Finally we can close the puppeteer instance and clean-up the file

  1. // teardown.js
  2. module.exports = async function() {
  3. // close the browser instance
  4. await global.__BROWSER__.close();
  5. // clean-up the wsEndpoint file
  6. rimraf.sync(DIR);
  7. };

With all the things set up, we can now write our tests like this:

  1. // test.js
  2. describe(
  3. '/ (Home Page)',
  4. () => {
  5. let page;
  6. beforeAll(async () => {
  7. page = await global.__BROWSER__.newPage();
  8. await page.goto('https://google.com');
  9. }, timeout);
  10. it('should load without error', async () => {
  11. await expect(page.title()).resolves.toMatch('Google');
  12. });
  13. },
  14. timeout,
  15. );

Here's the code of full working example.