Installations
npm install @mozilla/spawnd
Releases
Contributors
Developer
smooth-code
Developer Guide
Module System
CommonJS
Min. Node Version
Typescript Support
No
Node Version
12.16.1
NPM Version
lerna/3.19.0/node@v12.16.1+x64 (linux)
Statistics
3,539 Stars
410 Commits
288 Forks
38 Watching
5 Branches
71 Contributors
Updated on 11 Nov 2024
Bundle Size
4.55 kB
Minified
1.82 kB
Minified + Gzipped
Languages
TypeScript (91.16%)
JavaScript (6.92%)
HTML (1.92%)
Total Downloads
Cumulative downloads
Total Downloads
978
Last day
0%
1
Compared to previous day
Last week
-50%
1
Compared to previous week
Last month
37.5%
11
Compared to previous month
Last year
-23.2%
109
Compared to previous year
Daily Downloads
Weekly Downloads
Monthly Downloads
Yearly Downloads
Dependencies
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
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
Getting Started
Installation
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).
Basic Setup
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.
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
):
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.
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:
- Make sure your project is using the correct type definitions. If you’ve upgraded to version
10.1.2
or above, uninstall old types:
1npm uninstall --save-dev @types/jest-environment-puppeteer @types/expect-puppeteer
- Install
@types/jest
(jest-puppeteer
does not support@jest/globals
) :
1npm install --save-dev @types/jest
- 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:
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});
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:
1await expect(page).toMatchTextContent("Expected text");
- Simulate a button click:
1await expect(page).toClick("button", { text: "Submit" });
- Fill out a form:
1await expect(page).toFillForm('form[name="login"]', {
2 username: "testuser",
3 password: "password",
4});
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:
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.
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:
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.
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:
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.
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:
1// setup.js 2require("expect-puppeteer");
Then, in your Jest config:
1module.exports = { 2 setupFilesAfterEnv: ["./setup.js"], 3};
Extending 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;
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:
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 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 yourpackage.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
):
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.
API Reference
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 enhancedexpect
API provided byexpect-puppeteer
. You can use this to make assertions on the Puppeteerpage
.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 thepage
object before each test.Example:
1beforeEach(async () => { 2 await jestPuppeteer.resetPage(); 3});
-
global.jestPuppeteer.resetBrowser()
: Resets thebrowser
,context
, andpage
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.
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:
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.
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:
1await jestPuppeteer.debug();
To avoid test timeouts in CI, set a larger timeout during the debugging process:
1jest.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:
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.
Acknowledgements
Special thanks to Fumihiro Xue for providing an excellent Jest Puppeteer example, which served as an inspiration for this package.
No vulnerabilities found.
Reason
11 commit(s) and 5 issue activity found in the last 90 days -- score normalized to 10
Reason
no dangerous workflow patterns detected
Reason
no binaries found in the repo
Reason
license file detected
Details
- Info: project has a license file: LICENSE:0
- Info: FSF or OSI recognized license: MIT License: LICENSE:0
Reason
Found 7/23 approved changesets -- score normalized to 3
Reason
dependency not pinned by hash detected -- score normalized to 3
Details
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/ci.yml:16: update your workflow using https://app.stepsecurity.io/secureworkflow/argos-ci/jest-puppeteer/ci.yml/main?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/ci.yml:17: update your workflow using https://app.stepsecurity.io/secureworkflow/argos-ci/jest-puppeteer/ci.yml/main?enable=pin
- Info: 0 out of 2 GitHub-owned GitHubAction dependencies pinned
- Info: 1 out of 1 npmCommand dependencies pinned
Reason
8 existing vulnerabilities detected
Details
- Warn: Project is vulnerable to: GHSA-3xgq-45jj-v275
- Warn: Project is vulnerable to: GHSA-ff7x-qrg7-qggm
- Warn: Project is vulnerable to: GHSA-pfrx-2q88-qq97
- Warn: Project is vulnerable to: GHSA-rc47-6667-2j5j
- Warn: Project is vulnerable to: GHSA-35jh-r3h4-6jhm
- Warn: Project is vulnerable to: GHSA-44c6-4v22-4mhx
- Warn: Project is vulnerable to: GHSA-4x5v-gmq8-25ch
- Warn: Project is vulnerable to: GHSA-7p7h-4mm5-852v
Reason
detected GitHub workflow tokens with excessive permissions
Details
- Warn: no topLevel permission defined: .github/workflows/ci.yml:1
- Info: no jobLevel write permissions found
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
project is not fuzzed
Details
- Warn: no fuzzer integrations found
Reason
branch protection not enabled on development/release branches
Details
- Warn: branch protection not enabled for branch 'main'
Reason
security policy file not detected
Details
- Warn: no security policy file detected
- Warn: no security file to analyze
- Warn: no security file to analyze
- Warn: no security file to analyze
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
- Warn: 0 commits out of 20 are checked with a SAST tool
Score
4.1
/10
Last Scanned on 2024-11-18
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More