Installations
npm install jest-playwright-preset
Developer
playwright-community
Developer Guide
Module System
CommonJS
Min. Node Version
Typescript Support
Yes
Node Version
18.18.2
NPM Version
9.8.1
Statistics
532 Stars
692 Commits
75 Forks
12 Watching
3 Branches
27 Contributors
Updated on 05 Nov 2024
Languages
TypeScript (95.52%)
JavaScript (3.98%)
HTML (0.5%)
Total Downloads
Cumulative downloads
Total Downloads
57,687,035
Last day
-5%
182,808
Compared to previous day
Last week
1%
1,010,908
Compared to previous week
Last month
11.7%
4,264,223
Compared to previous month
Last year
134.9%
35,043,925
Compared to previous year
Daily Downloads
Weekly Downloads
Monthly Downloads
Yearly Downloads
Peer Dependencies
4
Dev Dependencies
23
Jest Playwright
⚠️ We recommend the official Playwright test-runner (@playwright/test) ⚠️
It's more flexible, lightweight, optimized for Playwright, and has TypeScript support out of the box. This doesn't mean, that we stop with maintaining this package.
Running your tests using Jest & Playwright
1npm install -D jest jest-playwright-preset playwright
Also you can use jest-playwright-preset
with specific playwright packages:
playwright-webkit
, playwright-chromium
and playwright-firefox
1npm install -D jest jest-playwright-preset playwright-firefox
Requirements
- Node.js 14+
- Playwright 1.2.0+
- Jest 28+
Usage
Update your Jest configuration, either:
with package.json
:
1"jest": { 2 "preset": "jest-playwright-preset" 3}
or with jest.config.js
:
1module.exports = { 2 preset: 'jest-playwright-preset', 3}
And add the Jest command as in the script section of your package.json
:
1{ 2 "scripts": { 3 "test": "jest" 4 } 5}
Now you can use Playwright in your tests:
1// example.test.js 2beforeAll(async () => { 3 await page.goto('https://whatismybrowser.com/') 4}) 5 6test('should display correct browser', async () => { 7 const browser = await page.$eval('.string-major', (el) => el.innerHTML) 8 expect(browser).toContain('Chrome') 9})
Notes
playwright
actions can take some time for execution, because of it jest-playwright
overrides jest default timeout interval from 5 to 15 seconds.
You can change this interval with testTimeout
in your jest
configuration.
Configuration
It's recommend to use a separate Jest configuration jest.e2e.config.js
for jest-playwright
to gain speed improvements and by that to only use Playwright in the end-to-end tests. For that you have to use the -c
flag when calling Jest and use the testMatch
or testRegex
in your Jest config to split them.
Be sure to remove any existing testEnvironment
option from your Jest configuration. The jest-playwright-preset
preset needs to manage that option itself.
Configuration options can be specified using a jest-playwright.config.js
file at the root of your project:
1// jest-playwright.config.js 2 3module.exports = { 4 // Options... 5}
Similar to Jest globalSetup configuration can except the export of an async function:
1module.exports = async () => { 2 await ... 3};
A custom path can be specified to the jest-playwright.config.js
file within your jest.config.js
file:
1process.env.JEST_PLAYWRIGHT_CONFIG = '/path/to/jest-playwright.config.js'
Alternatively, configuration options can specified using Jest's own testEnvironmentOptions
option within your jest.config.js
file:
1// jest.config.js 2 3module.exports = { 4 preset: 'jest-playwright-preset', 5 testEnvironmentOptions: { 6 'jest-playwright': { 7 // Options... 8 }, 9 }, 10}
Options
launchOptions
<[object]>. All Playwright launch options can be specified in config. Since it is JavaScript, you can use all stuff you need, including environment.launchType
<LAUNCH | PERSISTENT | SERVER>. Method to launch browser instance.jest-playwright
attaches Playwright to an existing browser instance by default.connectOptions
<[object]>. All Playwright connect options can be specified in config.contextOptions
<[object]>. All Playwright context options can be specified in config.- browsers <[(string | object)[]]>. Define browsers to run tests in.
chromium
Each test runs Chromium (default).firefox
Each test runs Firefox.webkit
Each test runs Webkit.
- devices <[(string | object)[] | RegExp]>. Define a devices to run tests in. Actual list of devices can be found here.
exitOnPageError
<[boolean]>. Exits process on any page error. Defaults totrue
.collectCoverage
<[boolean]>. Enables the coverage collection of thesaveCoverage(page)
calls to the.nyc_output/coverage.json
file.serverOptions
<[object]>. Alljest-process-manager
options.selectors
<[array]>. Define selectors. Each selector must be an object with name and script properties.skipInitialization
<[boolean]>. Add you ability to skip first setupplaywright
process. Possible use cases can be found hereresetContextPerTest
<[boolean]>. Option for opening a new context per testuseDefaultBrowserType
<[boolean]>. Sometimesbrowser
+device
combinations don't have any sense. With this option tests will be run withdefaultBrowserType
of device. Pay attention that you should define devices to correct usage of this option.
Usage of process environment to define browser
You can control the browser with passing environment variable.
1// jest-playwright.config.js 2module.exports = { 3 browsers: [process.env.BROWSER], 4}
Specific browser options
For launchOptions
, connectOptions
and contextOptions
you can define special browser options.
1// jest-playwright.config.js 2module.exports = { 3 connectOptions: { 4 chromium: { 5 wsEndpoint: 'ws://chrome.proxy.com:4444' 6 }, 7 firefox: { 8 wsEndpoint: 'ws://firefox.proxy.com:4444' 9 } 10 }, 11 ... 12}
Browser configuration
There are different ways to define devices in your configuration file:
- You can use array of browser names:
1module.exports = { 2 browsers: ["chromium", "webkit"], 3 ... 4}
- You can define custom browser. You can find out use cases here:
1{ 2 // Name of browser 3 name: 'chromium' | 'firefox' | 'webkit' 4 // Display name for test 5 displayName: string 6 ... 7 // Browser options 8}
Device configuration
There are different ways to define devices in your configuration file:
- You can use array of device names:
1module.exports = { 2 devices: ["iPhone 6", "Pixel 2"], 3 ... 4}
- You can use RegExp:
1module.exports = { 2 devices: /iPhone 8/, 3 ... 4}
- Also you can define custom device:
1{ 2 // Name of device 3 name: string 4 // Page width and height 5 viewport: { 6 width: number 7 height: number 8 } 9 // user agent 10 userAgent: string 11 // device scale factor 12 deviceScaleFactor: number 13 // is device is mobile 14 isMobile: boolean 15 // support of touch events 16 hasTouch: boolean 17 // device default browser 18 defaultBrowserType: chromium, firefox or webkit 19}
Globals
browserName
<[string]> - name of the current browser (chromium, firefox or webkit)deviceName
<[string]> - name of the current devicebrowser
<[Browser]> - Playwright browser instancecontext
<[Context]> - a new Playwright context instance for each new test filepage
<[Page]> - Playwright page instance (since a new context for every test file also creates a new page for it)
All of them are available globally in each Jest test. If you are using ESLint and JavaScript, its recommend to use it in combination with the eslint-plugin-jest-playwright.
Debug mode
Playwright give you ability to configure the browser for debugging with the PWDEBUG
environment variable. It will launch the browser in headful mode, disables playwright timeout and Jest won't timeout anymore.:
1PWDEBUG=1 jest
Reset helper functions
Reset current page
1beforeEach(async () => { 2 await jestPlaywright.resetPage() 3})
To create a new page for each test, you can use this snippet to have a new page object for each individual test.
Reset current context
1beforeEach(async () => { 2 await jestPlaywright.resetContext() 3})
To create a new context for each test, you can use this snippet to have a new context object for each individual test.
Reset current browser
1beforeEach(async () => { 2 await jestPlaywright.resetBrowser() 3})
You can use this snippet to reset current browser for each individual test. It will reset browser, context and page.
Debug helper functions
jest-playwright
provides some functions to debug your tests.
IMPORTANT NOTE: For these kind of tests you should use properties passed through callback function instead of globals
jestPlaywrightDebug
This helper function provide you ability to run specific tests in debug
mode. It will disable headless
mode.
You can find more information here
1test.jestPlaywrightDebug('failed', async ({ page }) => { 2 await page.goto('https://github.com/') 3 const title = await page.title() 4 await expect(title).toBe('Google') 5})
Also you can define options for debug
mode with debugOptions
:
1// jest-playwright.config.js 2module.exports = { 3 debugOptions: { 4 ... 5 contextOptions: { 6 offline: true 7 } 8 } 9 ... 10}
jestPlaywrightConfig
This helper function provide you ability to run specific tests with passed options.
You can define browser
and device
properties to run test for them, otherwise test run for current configuration.
1test.jestPlaywrightConfig(
2 {
3 // your jest-playwright options
4 },
5 'test name',
6 async ({ browser, context, page }) => {
7 /* ... */
8 },
9)
Tracking the coverage
It's possible to track the coverage of the end-to-end tests with the babel-plugin-istanbul Babel plugin configured. It needs to be included in the web application which you are gonna test otherwise it won't work. To use it, you have to set collectCoverage
in the jest-playwright.config.js
to true
. Per default the test coverage will be automatically saved after each navigation change (beforeunload
event). If a certain code path is not covered, you can manually call and add the corresponding saveCoverage(page)
call to your tests like that:
1await jestPlaywright.saveCoverage(page)
By using coverage collection, it will write the coverage data to the .nyc_output/coverage.json
file which can be transformed using nyc
to the lcov format:
npx nyc report --reporter=lcovonly
or to HTML:
npx nyc report --reporter=html
which will create a HTML website in the coverage
directory.
Skip tests for specific browsers and devices
It's possible to skip tests for browsers or combination of browsers and devices
1it.jestPlaywrightSkip( 2 { browsers: ['chromium'] }, 3 'should skip this one', 4 async () => { 5 const title = await page.title() 6 expect(title).toBe('Google') 7 }, 8)
Using shadow DOM selectors
Playwright engine pierces open shadow DOM by default.
1beforeAll(async () => { 2 await page.goto( 3 'https://mdn.github.io/web-components-examples/popup-info-box-web-component/', 4 ) 5}) 6 7test('should display "google" text on page', async () => { 8 const shadowElem = await page.$('.info') 9 const shadowElemText = await shadowElem.innerHTML() 10 11 expect(shadowElemText).toBe( 12 'Your card validation code (CVC) is an extra security feature — it is the last 3 or 4 numbers on the back of your card.', 13 ) 14})
Start a server
Jest Playwright integrates a functionality to start a server when running your test suite, like jest-puppeteer. It automatically closes the server when tests are done.
To use it, specify a server section in your jest-playwright.config.js
.
1// jest-playwright.config.js 2module.exports = { 3 serverOptions: { 4 command: 'node server.js', 5 port: 4444, 6 }, 7}
Other options are documented in jest-process-manager.
Using with different jest environments
The default jest-playwright environment is node, but you can use a browser-like environment through jest-playwright-jsdom
expect-playwright
There is a utility package expect-playwright which simplifies the expect statements in combination with Playwright to make e.g. shorter text comparisons.
ESLint globals / 'page' is not defined
There is an ESLint plugin available eslint-plugin-jest-playwright available which includes the globals for using jest-playwright.
Unstable and experimental API
You can run tests for multiple browsers and devices:
- You must have installed the playwright package
- You must define browsers to test with your
jest-playwright.config.js
:
1module.exports = { 2 browsers: ["chromium", "webkit"], 3 devices: ["iPhone 6", "Pixel 2"], 4 ... 5}
It will run your tests for:
- Chromium browser and iPhone 6 device;
- Chromium browser and Pixel 2 device;
- Webkit browser and iPhone 6 device;
- Webkit browser and Pixel 2 device;
If there is no defined browsers in config it will run tests for chromium browser.
Usage with custom testEnvironment
You can use jest-playwright with custom test environment for taking screenshots during test failures for example:
jest.config.json
1"testEnvironment": "./CustomEnvironment.js"
CustomEnvironment.js
1const PlaywrightEnvironment = 2 require('jest-playwright-preset/lib/PlaywrightEnvironment').default 3 4class CustomEnvironment extends PlaywrightEnvironment { 5 async setup() { 6 await super.setup() 7 // Your setup 8 } 9 10 async teardown() { 11 // Your teardown 12 await super.teardown() 13 } 14 15 async handleTestEvent(event) { 16 await super.handleTestEvent(event) 17 if (event.name === 'test_done' && event.test.errors.length > 0) { 18 const parentName = event.test.parent.name.replace(/\W/g, '-') 19 const specName = event.test.name.replace(/\W/g, '-') 20 21 await this.global.page.screenshot({ 22 path: `screenshots/${parentName}_${specName}.png`, 23 }) 24 } 25 } 26} 27 28module.exports = CustomEnvironment
Usage with custom runner
jest-playwright using custom runner underhood. So if you need implement your own runner
, you should extend it:
jest.config.json
1"runner": "./CustomRunner.js"
CustomRunner.js
1const PlaywrightRunner = 2 require('jest-playwright-preset/lib/PlaywrightRunner').default 3 4class CustomRunner extends PlaywrightRunner { 5 constructor(...args) { 6 super(...args) 7 this.isSerial = true 8 } 9} 10 11module.exports = CustomRunner
Usage with custom globalSetup
and globalTeardown
For this use case, jest-playwright-preset
exposes two methods: globalSetup
and globalTeardown
, so that you can wrap them with your own global setup and global teardown methods as the following example:
Getting authentication state once for all test cases as per playwright reference:
1// global-setup.js 2import { globalSetup as playwrightGlobalSetup } from 'jest-playwright-preset' 3 4module.exports = async function globalSetup(globalConfig) { 5 await playwrightGlobalSetup(globalConfig) 6 7 const browserServer = await chromium.launchServer() 8 const wsEndpoint = browserServer.wsEndpoint() 9 const browser = await chromium.connect({ wsEndpoint: wsEndpoint }) 10 const page = await browser.newPage() 11 12 // your login function 13 await doLogin(page) 14 15 // store authentication data 16 const storage = await page.context().storageState() 17 process.env.STORAGE = JSON.stringify(storage) 18}
1// global-teardown.js 2import { globalTeardown as playwrightGlobalTeardown } from 'jest-playwright-preset' 3 4module.exports = async function globalTeardown(globalConfig) { 5 // Your global teardown 6 await playwrightGlobalTeardown(globalConfig) 7}
Then assigning your js file paths to the globalSetup
and globalTeardown
property in your Jest configuration.
1{ 2 // ... 3 "globalSetup": "./global-setup.js", 4 "globalTeardown": "./global-teardown.js" 5}
Now your custom globalSetup
and globalTeardown
will be triggered once before and after all test suites.
Usage with Typescript
Example Jest configuration in combination with ts-jest:
1module.exports = { 2 preset: 'jest-playwright-preset', 3 transform: { 4 '^.+\\.ts$': 'ts-jest', 5 }, 6}
Types are also available, which you can either use via directly in your test:
1/// <reference types="jest-playwright-preset" /> 2/// <reference types="expect-playwright" />
or at your central tsconfig.json
either via files
:
1{ 2 "files": [ 3 "./global.d.ts", 4 "node_modules/jest-playwright-preset/types/global.d.ts", 5 "node_modules/expect-playwright/global.d.ts" 6 ] 7}
or via types
:
1{ 2 "compilerOptions": { 3 "types": ["jest-playwright-preset", "expect-playwright"] 4 } 5}
It's important to not change the testEnvironment
to node
. Otherwise it won't work.
Known issues
Error reporting with Jest
If you face into error messages like
UnhandledPromiseRejectionWarning: Error: Protocol error (Runtime.callFunctionOn): Target closed.
or
Timeout - Async callback was not invoked within the 20000ms timeout specified by jest.setTimeout.Timeout - Async callback was not invoked within the 20000ms timeout specified by jest.setTimeout.Error:
and your Jest error reporting will only show that an entire test (it()
function) has failed, then you need to increase the Jest timeout because the Playwright timeout is greater than the Jest timeout. So Jest in the end will simply stop the execution and no verbose (which exact line) error reporting can be generated.
To fix this behavior simply call
1jest.setTimeout(35 * 1000)
in your tests at the top. (30 seconds is the default Playwright timeout for waiting for an specific element.)
New Browser instance for each test
If for your individual tests a new entire browser instance spins up each time and it won't be reused, then you probably run them in parallel. If you run them in a synchronous way with the --runInBand
CLI option for Jest, then the same browser instance will be re-used and this should fix the issue.
Examples
Demonstration the usage of jest-playwright
for various test cases can be found in playwright-jest-examples
Inspiration
Thanks to Smooth Code for the great jest-puppeteer.
License
No vulnerabilities found.
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
dependency not pinned by hash detected -- score normalized to 4
Details
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/nodejs.yml:16: update your workflow using https://app.stepsecurity.io/secureworkflow/playwright-community/jest-playwright/nodejs.yml/main?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/nodejs.yml:18: update your workflow using https://app.stepsecurity.io/secureworkflow/playwright-community/jest-playwright/nodejs.yml/main?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/nodejs.yml:21: update your workflow using https://app.stepsecurity.io/secureworkflow/playwright-community/jest-playwright/nodejs.yml/main?enable=pin
- Warn: third-party GitHubAction not pinned by hash: .github/workflows/nodejs.yml:37: update your workflow using https://app.stepsecurity.io/secureworkflow/playwright-community/jest-playwright/nodejs.yml/main?enable=pin
- Info: 0 out of 3 GitHub-owned GitHubAction dependencies pinned
- Info: 0 out of 1 third-party GitHubAction dependencies pinned
- Info: 1 out of 1 npmCommand dependencies pinned
Reason
Found 8/28 approved changesets -- score normalized to 2
Reason
0 commit(s) and 1 issue activity found in the last 90 days -- score normalized to 0
Reason
detected GitHub workflow tokens with excessive permissions
Details
- Warn: no topLevel permission defined: .github/workflows/nodejs.yml:1
- Info: no jobLevel write permissions found
Reason
no effort to earn an OpenSSF best practices badge detected
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
project is not fuzzed
Details
- Warn: no fuzzer integrations found
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
- Warn: 0 commits out of 17 are checked with a SAST tool
Reason
11 existing vulnerabilities detected
Details
- Warn: Project is vulnerable to: GHSA-67hx-6x53-jw92
- Warn: Project is vulnerable to: GHSA-8hc4-vh64-cxmj
- Warn: Project is vulnerable to: GHSA-grv7-fg5c-xmjg
- Warn: Project is vulnerable to: GHSA-3xgq-45jj-v275
- Warn: Project is vulnerable to: GHSA-jchw-25xp-jwwc
- Warn: Project is vulnerable to: GHSA-cxjh-pqwp-8mfp
- Warn: Project is vulnerable to: GHSA-9c47-m6qq-7p4h
- Warn: Project is vulnerable to: GHSA-952p-6rrq-rcjv
- Warn: Project is vulnerable to: GHSA-c2qf-rxjj-qqgw
- Warn: Project is vulnerable to: GHSA-j8xg-fqg3-53r7
- Warn: Project is vulnerable to: GHSA-f9xv-q969-pqx4
Score
3.2
/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