Gathering detailed insights and metrics for jest-playwright-preset
Gathering detailed insights and metrics for jest-playwright-preset
Gathering detailed insights and metrics for jest-playwright-preset
Gathering detailed insights and metrics for jest-playwright-preset
npm install jest-playwright-preset
Module System
Min. Node Version
Typescript Support
Node Version
NPM Version
532 Stars
692 Commits
75 Forks
12 Watching
3 Branches
27 Contributors
Updated on 05 Nov 2024
TypeScript (95.52%)
JavaScript (3.98%)
HTML (0.5%)
Cumulative downloads
Total Downloads
Last day
-3.8%
193,014
Compared to previous day
Last week
2.2%
1,020,604
Compared to previous week
Last month
15.9%
4,258,384
Compared to previous month
Last year
135%
34,939,492
Compared to previous year
4
23
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
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})
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.
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}
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.chromium
Each test runs Chromium (default).firefox
Each test runs Firefox.webkit
Each test runs Webkit.exitOnPageError
<[boolean]>. Exits process on any page error. Defaults to true
.collectCoverage
<[boolean]>. Enables the coverage collection of the saveCoverage(page)
calls to the .nyc_output/coverage.json
file.serverOptions
<[object]>. All jest-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 setup playwright
process. Possible use cases can be found hereresetContextPerTest
<[boolean]>. Option for opening a new context per testuseDefaultBrowserType
<[boolean]>. Sometimes browser
+ device
combinations don't have any sense. With this option tests will be run with defaultBrowserType
of device. Pay attention that you should define devices to correct usage of this option.You can control the browser with passing environment variable.
1// jest-playwright.config.js 2module.exports = { 3 browsers: [process.env.BROWSER], 4}
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}
There are different ways to define devices in your configuration file:
1module.exports = { 2 browsers: ["chromium", "webkit"], 3 ... 4}
1{ 2 // Name of browser 3 name: 'chromium' | 'firefox' | 'webkit' 4 // Display name for test 5 displayName: string 6 ... 7 // Browser options 8}
There are different ways to define devices in your configuration file:
1module.exports = { 2 devices: ["iPhone 6", "Pixel 2"], 3 ... 4}
1module.exports = { 2 devices: /iPhone 8/, 3 ... 4}
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}
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.
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
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.
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.
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.
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
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}
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)
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.
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)
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})
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.
The default jest-playwright environment is node, but you can use a browser-like environment through jest-playwright-jsdom
There is a utility package expect-playwright which simplifies the expect statements in combination with Playwright to make e.g. shorter text comparisons.
'page' is not defined
There is an ESLint plugin available eslint-plugin-jest-playwright available which includes the globals for using jest-playwright.
You can run tests for multiple browsers and devices:
jest-playwright.config.js
:1module.exports = { 2 browsers: ["chromium", "webkit"], 3 devices: ["iPhone 6", "Pixel 2"], 4 ... 5}
It will run your tests for:
If there is no defined browsers in config it will run tests for chromium browser.
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
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
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:
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.
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.
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.)
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.
Demonstration the usage of jest-playwright
for various test cases can be found in playwright-jest-examples
Thanks to Smooth Code for the great jest-puppeteer.
No vulnerabilities found.
Reason
no dangerous workflow patterns detected
Reason
no binaries found in the repo
Reason
license file detected
Details
Reason
dependency not pinned by hash detected -- score normalized to 4
Details
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
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
security policy file not detected
Details
Reason
project is not fuzzed
Details
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
Reason
11 existing vulnerabilities detected
Details
Score
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 Morejest-process-manager
Starts a server before your Jest tests and tears it down after.
babel-preset-jest
> Babel preset for all Jest plugins. This preset is automatically included when using [babel-jest](https://github.com/jestjs/jest/tree/main/packages/babel-jest).
expect-playwright
![Node.js CI](https://github.com/playwright-community/expect-playwright/workflows/Node.js%20CI/badge.svg) [![codecov](https://codecov.io/gh/playwright-community/expect-playwright/branch/master/graph/badge.svg?token=Eay491HC49)](https://codecov.io/gh/playw
jest-preset-angular
Jest preset configuration for Angular projects