Using with puppeteer

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

    provides all required configuration to run your tests using Puppeteer.

    1. First, install jest-puppeteer
    1. Specify preset in your Jest configuration:
    1. {
    2. "preset": "jest-puppeteer"
    3. }
    1. Write your test

    There’s no need to load any dependencies. There’s no need to load any dependencies. Puppeteer’s page and browser classes will automatically be exposed

    Custom example without jest-puppeteer preset

    You can also hook up puppeteer from scratch. The basic idea is to: The basic idea is to:

    1. launch & file the websocket endpoint of puppeteer with Global Setup
    2. connect to puppeteer from each Test Environment
    3. close puppeteer with Global Teardown

    Here’s an example of the GlobalSetup script

    setup.js

    1. const {mkdir, writeFile} = require('fs').promises;
    2. const os = require('os');
    3. const path = require('path');
    4. const puppeteer = require('puppeteer');
    5. const DIR = path.join(os.tmpdir(), 'jest_puppeteer_global_setup');
    6. module.exports = async function () {
    7. const browser = await puppeteer.launch();
    8. // store the browser instance so we can teardown it later
    9. // this global is only available in the teardown but not in TestEnvironments
    10. global.__BROWSER_GLOBAL__ = browser;
    11. // use the file system to expose the wsEndpoint for TestEnvironments
    12. await mkdir(DIR, {recursive: true});
    13. await writeFile(path.join(DIR, 'wsEndpoint'), browser.wsEndpoint());
    14. };

    Then we need a custom Test Environment for puppeteer

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

    teardown.js

    1. const fs = require('fs').promises;
    2. const os = require('os');
    3. const path = require('path');
    4. module.exports = async function () {
    5. // close the browser instance
    6. await global.__BROWSER_GLOBAL__.close();
    7. // clean-up the wsEndpoint file
    8. await fs.rm(DIR, {recursive: true, force: true});
    9. };

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

    test.js

    1. module.exports = {
    2. globalSetup: './setup.js',
    3. globalTeardown: './teardown.js',
    4. testEnvironment: './puppeteer_environment.js',
    5. };

    Here’s the code of full working example.