Skip to content

Commit af89cc9

Browse files
DavertMikDavertMikclaude
authored
feat(playwright): instantAnimations option (#5797)
* feat(playwright): add instantAnimations and blockResources options instantAnimations sets the CDP Animation playback rate to 1000 on every page of a context (Chromium only), so clicks on animated elements no longer wait for the animation to finish. blockResources aborts requests of the listed resource types (image, media, font, stylesheet) through a context route. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(playwright): keep resource blocker when stopMockingRoute('**/*') is called Register the blockResources route with a predicate so unroute by URL pattern cannot remove it. Regenerate helper docs. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * refactor(playwright): move blockResources out of this change blockResources becomes an option for all web helpers in a separate change. This branch keeps instantAnimations only. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: DavertMik <davert@testomat.io> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1 parent b5be024 commit af89cc9

5 files changed

Lines changed: 148 additions & 0 deletions

File tree

‎docs/helpers/Playwright.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,7 @@ Type: [object][8]
7979
* `bypassCSP` **[boolean][26]?** bypass Content Security Policy or CSP
8080
* `highlightElement` **[boolean][26]?** highlight the interacting elements. Default: false. Note: only activate under verbose mode (--verbose).
8181
* `visibleLocator` **[boolean][26]?** append [`visible()`][49] to locators, so only visible elements are matched. Requires Playwright 1.63 or newer. Switch it off for a single step with `stepOpts({ visibleLocator: false })`. Not applied to `dragAndDrop`, which passes selectors to Playwright directly, nor to steps that must reach hidden elements: `grab*` methods, `scrollTo`, `seeElementInDOM`, `dontSeeElementInDOM` and `seeNumberOfElements`. When enabled, a locator matching only hidden elements fails as "element not found" instead of timing out on actionability, `strict` mode ignores hidden duplicates, and elements hidden by CSS (like a custom checkbox built on a visually hidden `input`) are no longer found.
82+
* `instantAnimations` **[boolean][26]?** run CSS transitions, CSS animations and Web Animations 1000 times faster, so a click waits for a moving element for one frame instead of the whole animation. `transitionend` and `animationend` still fire. Chromium only. Timers and JS-driven animations keep their speed. Not applied inside cross-origin iframes that Chromium runs in a separate process.
8283
* `recordHar` **[object][8]?** record HAR and will be saved to `output/har`. See more of [HAR options][3].
8384
* `testIdAttribute` **[string][7]?** locate elements based on the testIdAttribute. See more of [locate by test id][50].
8485
* `storageState` **([string][7] | [object][8])?** Playwright storage state (path to JSON file or object)

‎docs/playwright.md‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -464,6 +464,25 @@ I.stopMockingRoute('**/*.{png,jpg,jpeg}'
464464
465465
To master request intercepting [use `route` object](https://playwright.dev/docs/api/class-route) object passed into mock request handler.
466466
467+
## Instant Animations
468+
469+
Enable `instantAnimations` to cut the time a test spends waiting for animations:
470+
471+
```js
472+
helpers: {
473+
Playwright: {
474+
url: 'http://localhost:3000',
475+
instantAnimations: true,
476+
},
477+
}
478+
```
479+
480+
`instantAnimations` runs CSS transitions, CSS animations and Web Animations 1000 times faster on every page and tab. Playwright waits for an element to stop moving before clicking it, so a click on an element inside a 3 second transition takes about 100ms instead of 3 seconds. `transitionend` and `animationend` events still fire.
481+
482+
* Chromium only. Firefox and WebKit ignore the option.
483+
* `setTimeout`, `setInterval` and JavaScript-driven animations (like jQuery `animate`) keep their speed.
484+
* Not applied inside cross-origin iframes that Chromium runs in a separate process (site isolation).
485+
467486
## Video <Badge text="Since 3.1" type="warning"/>
468487
469488
Playwright may record videos for failed tests. This can be enabled in a config with `video: true` option:

‎lib/helper/Playwright.js‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -107,6 +107,7 @@ const pathSeparator = path.sep
107107
* @prop {boolean} [bypassCSP] - bypass Content Security Policy or CSP
108108
* @prop {boolean} [highlightElement] - highlight the interacting elements. Default: false. Note: only activate under verbose mode (--verbose).
109109
* @prop {boolean} [visibleLocator=false] - append [`visible()`](https://playwright.dev/docs/api/class-locator#locator-visible) to locators, so only visible elements are matched. Requires Playwright 1.63 or newer. Switch it off for a single step with `stepOpts({ visibleLocator: false })`. Not applied to `dragAndDrop`, which passes selectors to Playwright directly, nor to steps that must reach hidden elements: `grab*` methods, `scrollTo`, `seeElementInDOM`, `dontSeeElementInDOM` and `seeNumberOfElements`. When enabled, a locator matching only hidden elements fails as "element not found" instead of timing out on actionability, `strict` mode ignores hidden duplicates, and elements hidden by CSS (like a custom checkbox built on a visually hidden `input`) are no longer found.
110+
* @prop {boolean} [instantAnimations=false] - run CSS transitions, CSS animations and Web Animations 1000 times faster, so a click waits for a moving element for one frame instead of the whole animation. `transitionend` and `animationend` still fire. Chromium only. Timers and JS-driven animations keep their speed. Not applied inside cross-origin iframes that Chromium runs in a separate process.
110111
* @prop {object} [recordHar] - record HAR and will be saved to `output/har`. See more of [HAR options](https://playwright.dev/docs/api/class-browser#browser-new-context-option-record-har).
111112
* @prop {string} [testIdAttribute=data-testid] - locate elements based on the testIdAttribute. See more of [locate by test id](https://playwright.dev/docs/locators#locate-by-test-id).
112113
* @prop {string|object} [storageState] - Playwright storage state (path to JSON file or object)
@@ -419,6 +420,7 @@ class Playwright extends Helper {
419420
onResponse: null,
420421
strict: false,
421422
visibleLocator: false,
423+
instantAnimations: false,
422424
}
423425

424426
process.env.testIdAttribute = 'data-testid'
@@ -681,6 +683,7 @@ class Playwright extends Helper {
681683
throw err
682684
}
683685
}
686+
await this._setupContext(this.browserContext)
684687
}
685688
}
686689

@@ -695,6 +698,7 @@ class Playwright extends Helper {
695698
if (this.playwrightOptions.userDataDir) {
696699
this.browser = await playwright[this.options.browser].launchPersistentContext(this.userDataDir, this.playwrightOptions)
697700
this.browserContext = this.browser
701+
await this._setupContext(this.browserContext)
698702
const existingPages = await this.browserContext.pages()
699703
mainPage = existingPages[0]
700704
}
@@ -958,12 +962,14 @@ class Playwright extends Helper {
958962
throw new Error('Browser is not available for session context creation')
959963
}
960964
browserContext = await Promise.race([this.browser.newContext(Object.assign(this.contextOptions, config)), new Promise((_, reject) => setTimeout(() => reject(new Error('New context timeout')), 10000))])
965+
await this._setupContext(browserContext)
961966
page = await Promise.race([browserContext.newPage(), new Promise((_, reject) => setTimeout(() => reject(new Error('New page timeout')), 5000))])
962967
} catch (e) {
963968
console.warn('Warning during context creation:', e.message)
964969
if (this.playwrightOptions.userDataDir) {
965970
browserContext = await playwright[this.options.browser].launchPersistentContext(`${this.userDataDir}_${this.activeSessionName}`, this.playwrightOptions)
966971
this.browser = browserContext
972+
await this._setupContext(browserContext)
967973
page = await browserContext.pages()[0]
968974
} else {
969975
throw e
@@ -1231,6 +1237,7 @@ class Playwright extends Helper {
12311237
}
12321238
} else if (this.playwrightOptions.userDataDir) {
12331239
this.browser = await playwright[this.options.browser].launchPersistentContext(this.userDataDir, this.playwrightOptions)
1240+
await this._setupContext(this.browser)
12341241
} else {
12351242
this.browser = await playwright[this.options.browser].launch(this.playwrightOptions)
12361243
}
@@ -1244,6 +1251,25 @@ class Playwright extends Helper {
12441251
return this.browser
12451252
}
12461253

1254+
async _setupContext(context) {
1255+
if (!this.options.instantAnimations) return
1256+
if (this.options.browser !== 'chromium') {
1257+
this.debugSection('instantAnimations', 'supported in Chromium only, ignored')
1258+
return
1259+
}
1260+
1261+
const speedUp = async page => {
1262+
try {
1263+
const cdp = await context.newCDPSession(page)
1264+
await cdp.send('Animation.setPlaybackRate', { playbackRate: 1000 })
1265+
} catch (err) {
1266+
this.debugSection('instantAnimations', err.message)
1267+
}
1268+
}
1269+
context.on('page', speedUp)
1270+
for (const page of context.pages()) await speedUp(page)
1271+
}
1272+
12471273
/**
12481274
* Create a new browser context with a page. \
12491275
* Usually it should be run from a custom helper after call of `_startBrowser()`
@@ -1254,6 +1280,7 @@ class Playwright extends Helper {
12541280
throw new Error('Browser not started. Call _startBrowser() first or disable manualStart option.')
12551281
}
12561282
this.browserContext = await this.browser.newContext(contextOptions)
1283+
await this._setupContext(this.browserContext)
12571284

12581285
const page = await this.browserContext.newPage()
12591286
targetCreatedHandler.call(this, page)
@@ -1430,6 +1457,7 @@ class Playwright extends Helper {
14301457
throw err
14311458
}
14321459
}
1460+
await this._setupContext(this.browserContext)
14331461
}
14341462

14351463
let pages
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
<html>
2+
<head>
3+
<style>
4+
#moving { margin-left: 0; transition: margin-left 3s linear; }
5+
#moving.go { margin-left: 300px; }
6+
#spinning { animation: slide 3s linear; }
7+
@keyframes slide { from { margin-left: 0; } to { margin-left: 300px; } }
8+
</style>
9+
</head>
10+
<body>
11+
<button id="moving" onclick="window.clicked = true">Moving</button>
12+
<div id="spinning">Spinning</div>
13+
<script>
14+
window.ev = [];
15+
document.addEventListener('transitionend', function () { window.ev.push('transitionend') });
16+
document.addEventListener('animationend', function () { window.ev.push('animationend') });
17+
requestAnimationFrame(function () { requestAnimationFrame(function () { document.getElementById('moving').className = 'go' }) });
18+
</script>
19+
</body>
20+
</html>

‎test/helper/Playwright_test.js‎

Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1687,6 +1687,86 @@ describe('Playwright - Emulation', () => {
16871687
})
16881688
})
16891689

1690+
describe('Playwright - instantAnimations', function () {
1691+
this.timeout(35000)
1692+
1693+
describe('#instantAnimations', () => {
1694+
before(async () => {
1695+
global.codecept_dir = path.join(__dirname, '/../data')
1696+
I = new Playwright({
1697+
url: siteUrl,
1698+
browser: 'chromium',
1699+
show: false,
1700+
restart: false,
1701+
waitForAction: 0,
1702+
instantAnimations: true,
1703+
chrome: {
1704+
args: ['--no-sandbox', '--disable-setuid-sandbox'],
1705+
},
1706+
})
1707+
await I._init()
1708+
return I._beforeSuite()
1709+
})
1710+
1711+
beforeEach(() => I._before())
1712+
1713+
afterEach(() => I._after())
1714+
1715+
after(() => I._afterSuite())
1716+
1717+
it('should click an element in a 3s transition without waiting for it', async () => {
1718+
await I.amOnPage('/form/animations')
1719+
const start = Date.now()
1720+
await I.click('#moving')
1721+
expect(Date.now() - start).to.be.below(1000)
1722+
expect(await I.executeScript(() => window.clicked)).to.equal(true)
1723+
await I.waitForFunction(() => window.ev.length === 2, 2)
1724+
const events = await I.executeScript(() => window.ev)
1725+
expect(events).to.have.members(['transitionend', 'animationend'])
1726+
})
1727+
1728+
it('should speed up animations in a new tab', async () => {
1729+
await I.openNewTab()
1730+
await I.amOnPage('/form/animations')
1731+
const start = Date.now()
1732+
await I.click('#moving')
1733+
expect(Date.now() - start).to.be.below(1000)
1734+
})
1735+
})
1736+
1737+
describe('#instantAnimations disabled', () => {
1738+
before(async () => {
1739+
global.codecept_dir = path.join(__dirname, '/../data')
1740+
I = new Playwright({
1741+
url: siteUrl,
1742+
browser: 'chromium',
1743+
show: false,
1744+
restart: false,
1745+
waitForAction: 0,
1746+
chrome: {
1747+
args: ['--no-sandbox', '--disable-setuid-sandbox'],
1748+
},
1749+
})
1750+
await I._init()
1751+
return I._beforeSuite()
1752+
})
1753+
1754+
beforeEach(() => I._before())
1755+
1756+
afterEach(() => I._after())
1757+
1758+
after(() => I._afterSuite())
1759+
1760+
it('should keep animations at normal speed', async () => {
1761+
await I.amOnPage('/form/animations')
1762+
await I.wait(0.5)
1763+
const margin = await I.executeScript(() => parseFloat(getComputedStyle(document.getElementById('moving')).marginLeft))
1764+
expect(margin).to.be.below(300)
1765+
expect(await I.executeScript(() => window.ev)).to.eql([])
1766+
})
1767+
})
1768+
})
1769+
16901770
describe('Playwright - PERSISTENT', () => {
16911771
before(async () => {
16921772
global.codecept_dir = path.join(__dirname, '/../data')

0 commit comments

Comments
 (0)