Using with puppeteer

    note

    Generating code coverage for test files using Puppeteer is currently not possible if your test uses , 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.

    Jest Puppeteer provides all required configuration to run your tests using Puppeteer.

    1. First, install jest-puppeteer
    • npm
    • Yarn
    • pnpm
    1. yarn add --dev jest-puppeteer
    1. pnpm add --save-dev jest-puppeteer
    1. Specify preset in your :
    1. Write your test
    1. describe('Google', () => {
    2. beforeAll(async () => {
    3. await page.goto('https://google.com');
    4. });
    5. it('should be titled "Google"', async () => {
    6. await expect(page.title()).resolves.toMatch('Google');
    7. });
    8. });

    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:

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

    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. const DIR = path.join(os.tmpdir(), 'jest_puppeteer_global_setup');
    5. module.exports = async function () {
    6. await globalThis.__BROWSER_GLOBAL__.close();
    7. // clean-up the wsEndpoint file
    8. };

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

    test.js

    1. const timeout = 5000;
    2. describe(
    3. '/ (Home Page)',
    4. () => {
    5. let page;
    6. beforeAll(async () => {
    7. page = await globalThis.__BROWSER_GLOBAL__.newPage();
    8. await page.goto('https://google.com');
    9. }, timeout);
    10. it('should load without error', async () => {
    11. const text = await page.evaluate(() => document.body.textContent);
    12. expect(text).toContain('google');
    13. });
    14. },
    15. timeout,

    Here’s the code of .