You're Invited:Meet the Socket Team at BlackHat and DEF CON in Las Vegas, Aug 7-8.RSVP
Socket
Socket
Sign inDemoInstall

jest-environment-puppeteer

Package Overview
Dependencies
Maintainers
1
Versions
53
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

jest-environment-puppeteer

Puppeteer environment for Jest.


Version published
Weekly downloads
140K
decreased by-22.7%
Maintainers
1
Install size
15.4 MB
Created
Weekly downloads
 

Package description

What is jest-environment-puppeteer?

The jest-environment-puppeteer package provides a Jest test environment that uses Puppeteer, a headless Chrome Node API, to run browser tests. This allows you to write tests that interact with a real browser, making it ideal for end-to-end (E2E) testing, UI testing, and web scraping.

What are jest-environment-puppeteer's main functionalities?

End-to-End Testing

This feature allows you to perform end-to-end testing by interacting with a real browser. The code sample demonstrates how to navigate to Google's homepage and check if the text 'google' is present on the page.

const puppeteer = require('puppeteer');

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

  it('should display "google" text on page', async () => {
    const text = await page.evaluate(() => document.body.textContent);
    expect(text).toContain('google');
  });
});

UI Testing

This feature allows you to perform UI testing by simulating user interactions. The code sample demonstrates how to click a button on a webpage and verify that a message is displayed as a result.

const puppeteer = require('puppeteer');

describe('Button Click', () => {
  beforeAll(async () => {
    await page.goto('https://example.com');
  });

  it('should click a button and display a message', async () => {
    await page.click('#myButton');
    const message = await page.$eval('#message', el => el.textContent);
    expect(message).toBe('Button clicked!');
  });
});

Web Scraping

This feature allows you to perform web scraping by extracting information from web pages. The code sample demonstrates how to navigate to a webpage and scrape the title of the page.

const puppeteer = require('puppeteer');

describe('Web Scraping', () => {
  beforeAll(async () => {
    await page.goto('https://example.com');
  });

  it('should scrape the title of the page', async () => {
    const title = await page.title();
    expect(title).toBe('Example Domain');
  });
});

Other packages similar to jest-environment-puppeteer

Readme

Source

jest-environment-puppeteer

npm version npm dm npm dt

Run your tests using Jest & Puppeteer 🎪✨

npm install jest-environment-puppeteer puppeteer

Usage

Update your Jest configuration:

{
  "globalSetup": "jest-environment-puppeteer/setup",
  "globalTeardown": "jest-environment-puppeteer/teardown",
  "testEnvironment": "jest-environment-puppeteer"
}

Use Puppeteer in your tests:

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

  it('should display "google" text on page', async () => {
    const text = await page.evaluate(() => document.body.textContent);
    expect(text).toContain("google");
  });
});

API

global.browser

Give access to the Puppeteer Browser.

it("should open a new page", async () => {
  const page = await browser.newPage();
  await page.goto("https://google.com");
});

global.page

Give access to a Puppeteer Page opened at start (you will use it most of time).

it("should fill an input", async () => {
  await page.type("#myinput", "Hello");
});

global.context

Give access to a browser context that is instantiated when the browser is launched. You can control whether each test has its own isolated browser context using the browserContext option in config.

global.jestPuppeteer.debug()

Put test in debug mode.

  • Jest is suspended (no timeout)
  • A debugger instruction to Chromium, if Puppeteer has been launched with { devtools: true } it will stop
it("should put test in debug mode", async () => {
  await jestPuppeteer.debug();
});

global.jestPuppeteer.resetPage()

Reset global.page

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

global.jestPuppeteer.resetBrowser()

Reset global.browser, global.context, and global.page

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

Config

Jest Puppeteer uses cosmiconfig for configuration file support. This means you can configure Jest Puppeteer via (in order of precedence):

  • A "jest-puppeteer" key in your package.json file.
  • A .jest-puppeteerrc file written in JSON or YAML.
  • A .jest-puppeteerrc.json, .jest-puppeteerrc.yml, .jest-puppeteerrc.yaml, or .jest-puppeteerrc.json5 file.
  • A .jest-puppeteerrc.js, .jest-puppeteerrc.cjs, jest-puppeteer.config.js, or jest-puppeteer.config.cjs file that exports an object using module.exports.
  • A .jest-puppeteerrc.toml file.

By default it looks for config at the root of the project. You can define a custom path using JEST_PUPPETEER_CONFIG environment variable.

It should export a config object or a Promise that returns a config object.

interface JestPuppeteerConfig {
  /**
   * Puppeteer connect options.
   * @see https://pptr.dev/api/puppeteer.connectoptions
   */
  connect?: ConnectOptions;
  /**
   * Puppeteer launch options.
   * @see https://pptr.dev/api/puppeteer.launchoptions
   */
  launch?: PuppeteerLaunchOptions;
  /**
   * Server config for `jest-dev-server`.
   * @see https://www.npmjs.com/package/jest-dev-server
   */
  server?: JestDevServerConfig | JestDevServerConfig[];
  /**
   * Allow to run one browser per worker.
   * @default false
   */
  browserPerWorker?: boolean;
  /**
   * Browser context to use.
   * @default "default"
   */
  browserContext?: "default" | "incognito";
  /**
   * Exit on page error.
   * @default true
   */
  exitOnPageError?: boolean;
  /**
   * Use `runBeforeUnload` in `page.close`.
   * @see https://pptr.dev/api/puppeteer.page.close
   * @default false
   */
  runBeforeUnloadOnClose?: boolean;
}
Sync config
// jest-puppeteer.config.cjs

/** @type {import('jest-environment-puppeteer').JestPuppeteerConfig} */
module.exports = {
  launch: {
    dumpio: true,
    headless: process.env.HEADLESS !== "false",
  },
  server: {
    command: "node server.js",
    port: 4444,
    launchTimeout: 10000,
    debug: true,
  },
};
Async config

This example uses an already running instance of Chrome by passing the active web socket endpoint to connect. This is useful, for example, when you want to connect to Chrome running in the cloud.

// jest-puppeteer.config.cjs
const dockerHost = "http://localhost:9222";

async function getConfig() {
  const data = await fetch(`${dockerHost}/json/version`).json();
  const browserWSEndpoint = data.webSocketDebuggerUrl;
  /** @type {import('jest-environment-puppeteer').JestPuppeteerConfig} */
  return {
    connect: {
      browserWSEndpoint,
    },
    server: {
      command: "node server.js",
      port: 3000,
      launchTimeout: 10000,
      debug: true,
    },
  };
}

module.exports = getConfig();

Create custom environment

It is possible to create a custom environment from the Jest Puppeteer's one. It is not different from creating a custom environment from "jest-environment-node". See Jest testEnvironment documentation to learn more about it.

// my-custom-environment
const JestPuppeteerEnvironment =
  require("jest-environment-puppeteer").TestEnvironment;

class CustomEnvironment extends JestPuppeteerEnvironment {
  // Implement your own environment
}

Inspiration

Thanks to Fumihiro Xue for his great Jest example.

Keywords

FAQs

Package last updated on 15 Feb 2024

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc