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

    • First install jest-puppeteer

    yarn add —dev jest-puppeteer

    • Specify preset in your Jest configuration:
    • 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. });

    See .

    Custom example without jest-puppeteer preset

    You can also hook up puppeteer from scratch. 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

    Then we need a custom Test Environment for puppeteer

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

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

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

    Finally, set jest.config.js to read from these files. (The jest-puppeteer preset does something like this under the hood.)

    Here's the code of .