Gathering detailed insights and metrics for expect-puppeteer
Gathering detailed insights and metrics for expect-puppeteer
Gathering detailed insights and metrics for expect-puppeteer
Gathering detailed insights and metrics for expect-puppeteer
npm install expect-puppeteer
Module System
Min. Node Version
Typescript Support
Node Version
NPM Version
3,539 Stars
410 Commits
288 Forks
38 Watching
5 Branches
71 Contributors
Updated on 11 Nov 2024
Minified
Minified + Gzipped
TypeScript (91.16%)
JavaScript (6.92%)
HTML (1.92%)
Cumulative downloads
Total Downloads
Last day
-12.4%
38,805
Compared to previous day
Last week
-0.2%
218,033
Compared to previous week
Last month
6.8%
880,044
Compared to previous month
Last year
-6.4%
10,508,274
Compared to previous year
4
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
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.
To start using jest-puppeteer
, you’ll need to install the following packages:
1npm 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).
In your Jest configuration file (jest.config.js
), add jest-puppeteer
as the preset:
1{ 2 "preset": "jest-puppeteer" 3}
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.
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
):
1import "expect-puppeteer"; 2 3describe("Google Homepage", () => { 4 beforeAll(async () => { 5 await page.goto("https://google.com"); 6 }); 7 8 it('should display "google" text on page', async () => { 9 await expect(page).toMatchTextContent(/Google/); 10 }); 11});
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.
If you’re using TypeScript, jest-puppeteer
natively supports it from version 8.0.0
. To get started with TypeScript, follow these steps:
10.1.2
or above, uninstall old types:1npm uninstall --save-dev @types/jest-environment-puppeteer @types/expect-puppeteer
@types/jest
(jest-puppeteer
does not support @jest/globals
) :1npm install --save-dev @types/jest
@types/jest
. Once you’ve set up the environment, you can start writing tests in TypeScript just like in JavaScript:1import "jest-puppeteer"; 2import "expect-puppeteer"; 3 4describe("Google Homepage", (): void => { 5 beforeAll(async (): Promise<void> => { 6 await page.goto("https://google.com"); 7 }); 8 9 it('should display "google" text on page', async (): Promise<void> => { 10 await expect(page).toMatchTextContent(/Google/); 11 }); 12});
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.
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:
1await expect(page).toMatchTextContent("Expected text");
1await expect(page).toClick("button", { text: "Submit" });
1await expect(page).toFillForm('form[name="login"]', {
2 username: "testuser",
3 password: "password",
4});
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:
1await jestPuppeteer.debug();
To prevent the test from timing out, increase Jest’s timeout:
1jest.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.
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:
1module.exports = { 2 server: { 3 command: "node server.js", 4 port: 4444, 5 }, 6};
This eliminates the need to manually manage your server during testing.
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:
1module.exports = { 2 launch: { 3 product: "firefox", 4 headless: process.env.HEADLESS !== "false", 5 }, 6};
This file allows you to configure browser options, set up browser contexts, and more.
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:
1// setup.js 2require("expect-puppeteer");
Then, in your Jest config:
1module.exports = { 2 setupFilesAfterEnv: ["./setup.js"], 3};
PuppeteerEnvironment
For advanced use cases, you can extend the default PuppeteerEnvironment
class to add custom functionality:
1const PuppeteerEnvironment = require("jest-environment-puppeteer"); 2 3class CustomEnvironment extends PuppeteerEnvironment { 4 async setup() { 5 await super.setup(); 6 // Custom setup logic 7 } 8 9 async teardown() { 10 // Custom teardown logic 11 await super.teardown(); 12 } 13} 14 15module.exports = CustomEnvironment;
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:
1// global-setup.js 2const setupPuppeteer = require("jest-environment-puppeteer/setup"); 3 4module.exports = async function globalSetup(globalConfig) { 5 await setupPuppeteer(globalConfig); 6 // Additional setup logic 7};
In your Jest configuration, reference these files:
1{ 2 "globalSetup": "./global-setup.js", 3 "globalTeardown": "./global-teardown.js" 4}
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:
"jest-puppeteer"
key in your package.json
..jest-puppeteerrc
file (JSON, YAML, or JavaScript)..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
):
1module.exports = { 2 launch: { 3 headless: process.env.HEADLESS !== "false", 4 dumpio: true, // Show browser console logs 5 }, 6 browserContext: "default", // Use "incognito" if you want isolated sessions per test 7 server: { 8 command: "node server.js", 9 port: 4444, 10 launchTimeout: 10000, 11 debug: true, 12 }, 13};
You can further extend this configuration to connect to a remote instance of Chrome or customize the environment for your test runs.
Jest-Puppeteer exposes several global objects and methods to facilitate test writing:
global.browser
: Provides access to the Puppeteer Browser instance.
Example:
1const page = await browser.newPage(); 2await page.goto("https://example.com");
global.page
: The default Puppeteer Page object, automatically created and available in tests.
Example:
1await 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:
1await expect(page).toMatchTextContent("Expected text on page");
global.jestPuppeteer.debug()
: Suspends test execution, allowing you to inspect the browser and debug.
Example:
1await jestPuppeteer.debug();
global.jestPuppeteer.resetPage()
: Resets the page
object before each test.
Example:
1beforeEach(async () => { 2 await jestPuppeteer.resetPage(); 3});
global.jestPuppeteer.resetBrowser()
: Resets the browser
, context
, and page
objects, ensuring a clean slate for each test.
Example:
1beforeEach(async () => { 2 await jestPuppeteer.resetBrowser(); 3});
These methods simplify the setup and teardown process for tests, making it easier to work with Puppeteer in a Jest environment.
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:
1jest --runInBand
Alternatively, you can limit the number of parallel workers:
1jest --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.
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:
1await jestPuppeteer.debug();
To avoid test timeouts in CI, set a larger timeout during the debugging process:
1jest.setTimeout(600000); // 10 minutes
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:
1// .eslintrc.js 2module.exports = { 3 env: { 4 jest: true, 5 }, 6 globals: { 7 page: true, 8 browser: true, 9 context: true, 10 puppeteerConfig: true, 11 jestPuppeteer: true, 12 }, 13};
This configuration will prevent ESLint from throwing errors about undefined globals.
Special thanks to Fumihiro Xue for providing an excellent Jest Puppeteer example, which served as an inspiration for this package.
No vulnerabilities found.
No security vulnerabilities found.