Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

jest-environment-puppeteer

argos-ci708.4kMIT11.0.0TypeScript support: included

Puppeteer environment for Jest.

jest, jest-environment, puppeteer, jest-puppeteer, chromeless, chrome-headless

readme

Let's find a balance between detailed explanations and clarity. Here’s a more comprehensive version that retains structure but elaborates more where needed:


🎪 jest-puppeteer

npm version npm downloads

jest-puppeteer is a Jest preset designed for seamless integration with Puppeteer, enabling end-to-end testing in a browser environment. With a simple API, it allows you to launch browsers and interact with web pages, making it perfect for testing UI interactions in web applications.

Table of Contents

  1. Getting Started
  2. Recipes
  3. Jest-Puppeteer Configuration
  4. API Reference
  5. Troubleshooting
  6. Acknowledgements

Getting Started

Installation

To start using jest-puppeteer, you’ll need to install the following packages:

npm install --save-dev jest-puppeteer puppeteer jest

This will install Jest (the testing framework), Puppeteer (the headless browser tool), and jest-puppeteer (the integration between the two).

Basic Setup

In your Jest configuration file (jest.config.js), add jest-puppeteer as the preset:

{
  "preset": "jest-puppeteer"
}

This will configure Jest to use Puppeteer for running your tests. Make sure to remove any conflicting testEnvironment settings that might be present in your existing Jest configuration, as jest-puppeteer manages the environment for you.

Writing Your First Test

Once you’ve configured Jest, you can start writing tests using Puppeteer’s page object, which is automatically provided by jest-puppeteer.

Create a test file (e.g., google.test.js):

import "expect-puppeteer";

describe("Google Homepage", () => {
  beforeAll(async () => {
    await page.goto("https://google.com");
  });

  it('should display "google" text on page', async () => {
    await expect(page).toMatchTextContent(/Google/);
  });
});

This example test navigates to Google’s homepage and checks if the page contains the word "Google". jest-puppeteer simplifies working with Puppeteer by exposing the page object, allowing you to write tests using a familiar syntax.

TypeScript Setup

If you’re using TypeScript, jest-puppeteer natively supports it from version 8.0.0. To get started with TypeScript, follow these steps:

  1. Make sure your project is using the correct type definitions. If you’ve upgraded to version 10.1.2 or above, uninstall old types:
npm uninstall --save-dev @types/jest-environment-puppeteer @types/expect-puppeteer
  1. Install @types/jest (jest-puppeteer does not support @jest/globals) :
npm install --save-dev @types/jest
  1. Jest will automatically pick up type definitions from @types/jest. Once you’ve set up the environment, you can start writing tests in TypeScript just like in JavaScript:
import "jest-puppeteer";
import "expect-puppeteer";

describe("Google Homepage", (): void => {
  beforeAll(async (): Promise<void> => {
    await page.goto("https://google.com");
  });

  it('should display "google" text on page', async (): Promise<void> => {
    await expect(page).toMatchTextContent(/Google/);
  });
});

Visual Testing with Argos

Argos is a powerful tool for visual testing, allowing you to track visual changes introduced by each pull request. By integrating Argos with jest-puppeteer, you can easily capture and compare screenshots to maintain the visual consistency of your application.

To get started, check out the Puppeteer Quickstart Guide.

Recipes

Using expect-puppeteer

Writing tests with Puppeteer’s core API can be verbose. The expect-puppeteer library simplifies this by adding custom matchers, such as checking for text content or interacting with elements. Some examples:

  • Assert that a page contains certain text:
await expect(page).toMatchTextContent("Expected text");
  • Simulate a button click:
await expect(page).toClick("button", { text: "Submit" });
  • Fill out a form:
await expect(page).toFillForm('form[name="login"]', {
  username: "testuser",
  password: "password",
});

Debugging Tests

Debugging can sometimes be tricky in headless browser environments. jest-puppeteer provides a helpful debug() function, which pauses test execution and opens the browser for manual inspection:

await jestPuppeteer.debug();

To prevent the test from timing out, increase Jest’s timeout:

jest.setTimeout(300000); // 5 minutes

This can be particularly useful when you need to step through interactions or inspect the state of the page during test execution.

Automatic Server Management

If your tests depend on a running server (e.g., an Express app), you can configure jest-puppeteer to automatically start and stop the server before and after tests:

module.exports = {
  server: {
    command: "node server.js",
    port: 4444,
  },
};

This eliminates the need to manually manage your server during testing.

Customizing the Puppeteer Instance

You can easily customize the Puppeteer instance used in your tests by modifying the jest-puppeteer.config.js file. For example, if you want to launch Firefox instead of Chrome:

module.exports = {
  launch: {
    browser: "firefox",
    headless: process.env.HEADLESS !== "false",
  },
};

This file allows you to configure browser options, set up browser contexts, and more.

Custom Test Setup

If you have custom setup requirements, you can define setup files to initialize your environment before each test. For instance, you may want to import expect-puppeteer globally:

// setup.js
require("expect-puppeteer");

Then, in your Jest config:

module.exports = {
  setupFilesAfterEnv: ["./setup.js"],
};

Extending PuppeteerEnvironment

For advanced use cases, you can extend the default PuppeteerEnvironment class to add custom functionality:

const PuppeteerEnvironment = require("jest-environment-puppeteer");

class CustomEnvironment extends PuppeteerEnvironment {
  async setup() {
    await super.setup();
    // Custom setup logic
  }

  async teardown() {
    // Custom teardown logic
    await super.teardown();
  }
}

module.exports = CustomEnvironment;

Global Setup and Teardown

Sometimes, tests may require a global setup or teardown step that only runs once per test suite. You can define custom globalSetup and globalTeardown scripts:

// global-setup.js
const setupPuppeteer = require("jest-environment-puppeteer/setup");

module.exports = async function globalSetup(globalConfig) {
  await setupPuppeteer(globalConfig);
  // Additional setup logic
};

In your Jest configuration, reference these files:

{
  "globalSetup": "./global-setup.js",
  "globalTeardown": "./global-teardown.js"
}

Jest-Puppeteer Configuration

Jest-Puppeteer supports various configuration formats through cosmiconfig, allowing flexible ways to define your setup. By default, the configuration is looked for at the root of your project, but you can also define a custom path using the JEST_PUPPETEER_CONFIG environment variable.

Possible configuration formats:

  • A "jest-puppeteer" key in your package.json.
  • A .jest-puppeteerrc file (JSON, YAML, or JavaScript).
  • A .jest-puppeteer.config.js or .jest-puppeteer.config.cjs file that exports a configuration object.

Example of a basic configuration file (jest-puppeteer.config.js):

module.exports = {
  launch: {
    headless: process.env.HEADLESS !== "false",
    dumpio: true, // Show browser console logs
  },
  browserContext: "default", // Use "incognito" if you want isolated sessions per test
  server: {
    command: "node server.js",
    port: 4444,
    launchTimeout: 10000,
    debug: true,
  },
};

You can further extend this configuration to connect to a remote instance of Chrome or customize the environment for your test runs.

API Reference

Jest-Puppeteer exposes several global objects and methods to facilitate test writing:

  • global.browser: Provides access to the Puppeteer Browser instance.

    Example:

    const page = await browser.newPage();
    await page.goto("https://example.com");
  • global.page: The default Puppeteer Page object, automatically created and available in tests.

    Example:

    await page.type("#input", "Hello World");
  • global.context: Gives access to the browser context, useful for isolating tests in separate contexts.

  • global.expect(page): The enhanced expect API provided by expect-puppeteer. You can use this to make assertions on the Puppeteer page.

    Example:

    await expect(page).toMatchTextContent("Expected text on page");
  • global.jestPuppeteer.debug(): Suspends test execution, allowing you to inspect the browser and debug.

    Example:

    await jestPuppeteer.debug();
  • global.jestPuppeteer.resetPage(): Resets the page object before each test.

    Example:

    beforeEach(async () => {
      await jestPuppeteer.resetPage();
    });
  • global.jestPuppeteer.resetBrowser(): Resets the browser, context, and page objects, ensuring a clean slate for each test.

    Example:

    beforeEach(async () => {
      await jestPuppeteer.resetBrowser();
    });

These methods simplify the setup and teardown process for tests, making it easier to work with Puppeteer in a Jest environment.

Troubleshooting

CI Timeout Issues

In CI environments, tests may occasionally time out due to limited resources. Jest-Puppeteer allows you to control the number of workers used to run tests. Running tests serially can help avoid these timeouts:

Run tests in a single process:

jest --runInBand

Alternatively, you can limit the number of parallel workers:

jest --maxWorkers=2

This ensures that your CI environment doesn’t get overloaded by too many concurrent processes, which can improve the reliability of your tests.

Debugging CI Failures

Sometimes, failures happen only in CI environments and not locally. In such cases, use the debug() method to open a browser during CI runs and inspect the page manually:

await jestPuppeteer.debug();

To avoid test timeouts in CI, set a larger timeout during the debugging process:

jest.setTimeout(600000); // 10 minutes

Preventing ESLint Errors with Global Variables

Jest-Puppeteer introduces global variables like page, browser, context, etc., which ESLint may flag as undefined. You can prevent this by adding these globals to your ESLint configuration:

// .eslintrc.js
module.exports = {
  env: {
    jest: true,
  },
  globals: {
    page: true,
    browser: true,
    context: true,
    puppeteerConfig: true,
    jestPuppeteer: true,
  },
};

This configuration will prevent ESLint from throwing errors about undefined globals.

Acknowledgements

Special thanks to Fumihiro Xue for providing an excellent Jest Puppeteer example, which served as an inspiration for this package.

changelog

Change Log

All notable changes to this project will be documented in this file. See Conventional Commits for commit guidelines.

11.0.0 (2024-12-21)

Features

BREAKING CHANGES

  • Node.js v16 is not supported

10.1.4 (2024-10-26)

Bug Fixes

  • revert types resolution from @jest/globals (#604) (4bc420b)

10.1.3 (2024-10-22)

Bug Fixes

  • fix types resolution when importing jest types from @jest/globals (#602) (e5b2e1a)

10.1.2 (2024-10-10)

Bug Fixes

  • fix types resolution for expect-puppeteer (#599) (37e3271)

10.1.1 (2024-09-06)

Note: Version bump only for package jest-puppeteer

10.1.0 (2024-08-17)

Features

10.0.1 (2024-02-15)

Bug Fixes

10.0.0 (2024-02-10)

Features

BREAKING CHANGES

  • Drop Node.js v16 support.

9.0.2 (2023-12-06)

Bug Fixes

9.0.1 (2023-10-01)

Bug Fixes

  • fix compatibility with Puppeteer v21 (#566) (5cfee1f)

9.0.0 (2023-05-24)

Bug Fixes

  • expect-puppeteer: fix addSnapshotSerializer usage (826fd31), closes #552
  • jest-dev-server: no default host (c35e403)
  • jest-dev-server: properly detect if port is used, using both config.port and config.host options. (351720a), closes #555
  • types: fix environment global types (fb691f7)
  • types: fix missing jestPuppeteer global before setup (37e2294)

Features

  • drop Node.js v14 support (d7d9833)

BREAKING CHANGES

  • drop Node.js v14 support
  • jest-dev-server: default host is now undefined instead of "localhost"

8.0.6 (2023-03-24)

Bug Fixes

8.0.5 (2023-03-09)

Bug Fixes

  • spawnd: remove exit dependency (af2eb01), closes #541

8.0.4 (2023-03-08)

Bug Fixes

8.0.3 (2023-03-07)

Bug Fixes

  • avoid creating screenshots directory (d9e58fe), closes #521
  • jest-puppeteer: fix preset export (82e4163), closes #528

8.0.2 (2023-03-06)

Bug Fixes

8.0.1 (2023-03-06)

Bug Fixes

  • remove cycle dependency (ed5c9eb)

8.0.0 (2023-03-06)

Features

BREAKING CHANGES

    • spawnd now exports { spawd } instead of default to ensure compatibilty with ESM
  • toMatch has been renamed toMatchTextContent to avoid collision with existing Jest matcher

7.0.1 (2023-02-15)

Bug Fixes

7.0.0 (2023-02-03)

Features

BREAKING CHANGES

  • requires puppeteer v19+

6.2.0 (2022-12-11)

Bug Fixes

Features

6.1.1 (2022-07-06)

Bug Fixes

  • expect-puppeteer: return proper error stack traces from matchers (#487) (e9cafb1)
  • prevent stdout buffer from filling up (#482) (6f16345)

6.1.0 (2022-02-02)

Features

  • add traverseShadowRoots option to toMatch (#463) (28c5235)

6.0.3 (2021-12-14)

Bug Fixes

  • avoid running connect in global setup if browserWSEndpoint provided in config (#458) (c9fa515)

6.0.2 (2021-11-25)

Bug Fixes

6.0.1 (2021-11-24)

Bug Fixes

  • Catch exceptions on browser close or disconnect during teardown (#453) (adafcc2)

6.0.0 (2021-09-23)

Bug Fixes

BREAKING CHANGES

  • drop support for node v10

5.0.4 (2021-05-26)

Bug Fixes

5.0.3 (2021-04-28)

Bug Fixes

5.0.2 (2021-04-21)

Bug Fixes

5.0.1 (2021-04-19)

Bug Fixes

  • add jest-environment-node as a dependency (#397) (11f2e38)

5.0.0 (2021-04-16)

Bug Fixes

  • Leverage Puppeteer's native support for Firefox (#356) (e54fb7e)
  • require to puppeteer-core as fallback (#315) (49d313c)
  • Resolve module paths in preset (#335) (36602a1)
  • toFill doesn't empty contents when given an empty string (#381) (964b9a2)

Features

BREAKING CHANGES

  • browser config is deprecated. Use launch.product instead.
  • jest-dev-server uses axios instead of request so the waitOnScheme options may have changed. see wait-on v5.0.0 changelog for more details

4.4.0 (2019-12-18)

Bug Fixes

Features

  • increase peerDependencies to allow Puppeteer v2 (#289) (62a9b81)
  • expect-puppeteer: support frames (#275) (09703ea)

4.3.0 (2019-07-14)

Bug Fixes

Features

  • add jestPuppeteer.resetBrowser method (#237) (ae93739)

4.2.0 (2019-05-28)

Bug Fixes

  • jest-dev-server can't detect used ports (#235) (8b64c10)

Features

4.1.1 (2019-04-11)

Bug Fixes

  • do not attempt to start the server when usedPortAction is ignore and isPortTaken is true (#219) (7df3721)

4.1.0 (2019-03-14)

Bug Fixes

  • invalid connect options, when using browserURL (#212) (6e483e6)

Features

  • expect-puppeteer: add visibility option to toMatchElement (#208) (46d8ec1)

4.0.0 (2019-02-13)

Bug Fixes

  • Cannot read property watch of undefined in jest v22 version (#197) (db731a3)

Features

BREAKING CHANGES

  • v4.x is only compatible with Jest v24, use v3.x with Jest v23.

3.9.0 (2019-01-22)

Bug Fixes

  • jest --watch fails to reload (#182) (cc9bbfa)
  • wrong timeout when using jestPuppeteer.debug() (#185) (0f4c720)

Features

3.8.0 (2019-01-11)

Bug Fixes

  • disconnect the browser on environment teardown (#173) (5d073cc)

Features

  • jest-environment-puppeteer: accept a promise as config (#178) (40bc3a2)

3.7.0 (2018-12-11)

Features

3.6.0 (2018-12-06)

Bug Fixes

  • skip closing external browser on teardown (0505b2c)
  • use browser.disconnect method (7afbb2e)

Features

  • jest-dev-server: support multiple servers (#163) (6cf690c)

3.5.2 (2018-11-27)

Bug Fixes

3.5.1 (2018-11-11)

Bug Fixes

  • avoid prompting for super user login (as possible) (#149) (1701e9b)

3.5.0 (2018-11-04)

Bug Fixes

  • jest-dev-server: do not require port to run server (5aee5fe), closes #146
  • jest-dev-server: do not scan process if usedPortAction is "ignore" (cceb0bd), closes #96

Features

Performance Improvements

3.4.0 (2018-09-24)

Bug Fixes

  • support several instances of Jest in parallel (#138) (275bc71)

Features

  • expect-puppeteer: Update default options to look at connect object (1f33ea0)
  • jest-environment-puppeteer: Add ability to connect to an already existing instance of Chrome (9de05f0)
  • jest-environment-puppeteer: Add documentation of new connectoptions (c6b0613)
  • jest-environment-puppeteer: Remove unneeded async config (30a3daa)
  • jest-environment-puppeteer: Simplify getBrowser function (8ccb0d0)

3.3.1 (2018-08-17)

Bug Fixes

  • revert pid based endpoint file (4a08847), closes #103

3.3.0 (2018-08-15)

Bug Fixes

  • jest-dev-server: support for port being held by System Idle Process (#95) (e454973)

Features

  • jest-dev-server: add support for protocol & host (#93) (5dca53b)
  • add support for defaultViewport option (7b484a8)
  • support multiple processes on same machine (#103) (4d37d17)

3.2.1 (2018-06-17)

Bug Fixes

3.2.0 (2018-06-17)

Bug Fixes

  • jest-dev-server: fix watch mode stdin after ask (a7ca57b)

Features

3.1.0 (2018-06-16)

Features

  • jest-dev-server: externalize it & auto-kill (45e8fbb), closes #66 #68

3.0.1 (2018-05-03)

Bug Fixes

  • expect-puppeteer: use the same behaviour on toMatch and toMatchElement (784bde8)

3.0.0 (2018-05-03)

Features

  • expect-puppeteer: added delay option to element.type for toFill matcher (#52) (ee39ba9)
  • expect-puppeteer: enhance toMatchElement / toClick text option (cee8f46), closes #51 #50

BREAKING CHANGES

  • expect-puppeteer: Text is now trimmed and no longer evaluated as a RegExp. If you want this behaviour, use a true RegExp.

2.4.0 (2018-04-24)

Features

  • expect-puppeteer: keep original error message (#45) (72b60a9), closes #33
  • expect-puppeteer: make default options configurable (#46) (0d493c4)
  • adjust default timeout with slowMo (6871ec8), closes #36
  • jest-environment-puppeteer: add server.launchTimeout & server.debug options (e312717), closes #44
  • jest-environment-puppeteer: added config option for global err msg (#35) (d87c99a), closes #34

2.3.0 (2018-04-06)

Features

  • jest-environment-puppeteer: support custom config (6cd3050), closes #19

2.2.3 (2018-04-03)

Bug Fixes

  • support ignoreHTTPSErrors launch option (ed60439)

2.2.2 (2018-04-01)

Bug Fixes

2.2.1 (2018-03-25)

Bug Fixes

  • support original Jest matchers (99d542e), closes #17

2.2.0 (2018-03-17)

Features

2.1.0 (2018-03-16)

Features

  • add element handle support (4d37d5b)

2.0.1 (2018-03-08)

Bug Fixes

  • expect-puppeteer: fix expectMatch when body is undefined (#9) (0c60970)

2.0.0 (2018-03-05)

Bug Fixes

  • add missing await to README (cb11763)

Features

BREAKING CHANGES

  • expectPage() is replaced by expect(page)
  • Puppeteer launch options are now specified under launch object

1.1.1 (2018-03-04)

Bug Fixes

  • expect-puppeteer: add all sources in pkg (bb51870)

1.1.0 (2018-03-04)

Features

  • add jest-puppeteer-preset (7fbb273)
  • add spawnd & expect-puppeteer (6b7f5a4)

1.0.1 (2018-03-03)

Move to Lerna.

1.0.0 (2018-03-03)

feta

  • simplify API

BREAKING CHANGES

    • mainPage is renamed into page
  • "/globalSetup" => "/setup"

  • "/globalTeardown" => "/teardown"
  • "/testEnvironment" => ""

0.2.0 (2018-03-03)

Features

  • support Puppeteer configuration

0.1.0 (2018-03-02)

Features

  • first version 🎉