Skip to content

Commit 4c7b9c3

Browse files
DavertMikDavertMikclaude
authored
feat(retryFailedStep): wakeOnChange retries as soon as the page changes, across all web helpers (#5799)
* feat(retryFailedStep): wakeOnChange option to retry as soon as the page changes Recorder retry rules accept an optional async beforeRetry(number). When set, promise-retry runs with zero timeouts and the rule awaits beforeRetry before each retry attempt. Rules without it behave as before. retryFailedStep gets a wakeOnChange option (default false). When enabled, it waits for _waitForChange(delay) on the first helper that implements it, with the usual backoff delay as an upper bound, and sleeps otherwise. Playwright implements _waitForChange with a MutationObserver on the page document raced against a timer; navigation counts as a change. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * feat(retryFailedStep): support wakeOnChange in Puppeteer, WebDriver and CDPBrowser The in-page MutationObserver script moves to lib/helper/scripts/waitForChange.js and is shared by Playwright, Puppeteer, WebDriver and CDPBrowser (and their subclasses). WebDriver runs it with executeAsync; a navigation or stale-context error counts as a change, other errors (e.g. native Appium context) fall back to the backoff timer. _waitForChange tests move to the shared webapi spec. wakeOnChange is documented in docs/retry.md. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test(webapi): skip _waitForChange navigation case on Obscura 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 3291a3f commit 4c7b9c3

12 files changed

Lines changed: 288 additions & 1 deletion

File tree

‎docs/plugins/retryFailedStep.md‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,7 @@ Run tests with plugin enabled:
4343
You can use step names or step prefixes ending with `*`. As such, `wait*` will match all steps starting with `wait`.
4444
To append your own steps to ignore list - copy and paste a default steps list. Regexp values are accepted as well.
4545
* `deferToScenarioRetries` - when enabled (default), step retries are automatically disabled if scenario retries are configured to avoid excessive total retries.
46+
* `wakeOnChange` - when enabled, a failed step is retried as soon as the page changes (DOM mutation or navigation) instead of sleeping through the whole backoff. The backoff delay is still the upper bound. Default is false.
4647

4748
#### Example
4849

@@ -58,6 +59,17 @@ plugins: {
5859
}
5960
```
6061

62+
Retry as soon as the page changes:
63+
64+
```js
65+
plugins: {
66+
retryFailedStep: {
67+
enabled: true,
68+
wakeOnChange: true,
69+
}
70+
}
71+
```
72+
6173
#### Disable Per Test
6274

6375
This plugin can be disabled per test. In this case you will need to add `step.retry()` to all flaky steps:

‎docs/retry.md‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -109,6 +109,21 @@ element not found => 0 + (1s+1s) = 2s
109109
element found but not interactable => 3×5s + (1s+1s) = 17s
110110
```
111111

112+
### Retry on Page Change
113+
114+
With `wakeOnChange`, a failed step is retried as soon as the page changes (a DOM mutation or a navigation) instead of sleeping through the whole gap. The gap above stays the upper bound, so on a page that doesn't change the timing is the same:
115+
116+
```js
117+
plugins: {
118+
retryFailedStep: {
119+
enabled: true,
120+
wakeOnChange: true,
121+
}
122+
}
123+
```
124+
125+
A step waiting for content that shows up 400ms later passes on that change instead of on the next scheduled retry. A retry can fire in the middle of a render and fail again, which uses up a retry sooner. The option is disabled by default.
126+
112127
## Manual Step Retries
113128

114129
Retry a specific step known to be flaky:

‎lib/helper/CDPBrowser.js‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import CDPConnection from './extras/CDPConnection.js'
88
import installCodeceptClient from './clientscripts/cdpBrowserClient.js'
99
import xpathPolyfillSource from './clientscripts/xpathPolyfill.js'
1010
import layoutProbe from './clientscripts/layoutProbe.js'
11+
import { waitForChange } from './scripts/waitForChange.js'
1112
import { ariaSnapshotFromAXNodes } from '../aria.js'
1213
import Locator from '../locator.js'
1314
import output from '../output.js'
@@ -542,6 +543,16 @@ class CDPBrowser extends Helper {
542543
return res.result ? res.result.value : undefined
543544
}
544545

546+
async _waitForChange(ms) {
547+
const change = this._evaluate(`(${waitForChange})(${ms})`).catch(() => {})
548+
let timer
549+
const wait = new Promise(resolve => {
550+
timer = setTimeout(resolve, ms)
551+
})
552+
await Promise.race([wait, change])
553+
clearTimeout(timer)
554+
}
555+
545556
async _ensureClient() {
546557
const installed = await this._evaluate(`typeof window.__codecept !== 'undefined'`)
547558
if (installed) return

‎lib/helper/Playwright.js‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,7 @@ import Downloads from './extras/Download.js'
4141
import Console from './extras/Console.js'
4242
import { findByPlaywrightLocator } from './extras/PlaywrightLocator.js'
4343
import { dropFile } from './scripts/dropFile.js'
44+
import { waitForChange } from './scripts/waitForChange.js'
4445
import WebElement from '../element/WebElement.js'
4546
import { selectElement } from './extras/elementSelection.js'
4647
import { fillRichEditor } from './extras/richTextEditor.js'
@@ -1193,6 +1194,16 @@ class Playwright extends Helper {
11931194
return this.executeScript(() => window.location.href)
11941195
}
11951196

1197+
async _waitForChange(ms) {
1198+
const change = this.page.evaluate(waitForChange, ms).catch(() => {})
1199+
let timer
1200+
const wait = new Promise(resolve => {
1201+
timer = setTimeout(resolve, ms)
1202+
})
1203+
await Promise.race([wait, change])
1204+
clearTimeout(timer)
1205+
}
1206+
11961207
/**
11971208
* Grab the text within the popup. If no popup is visible then it will return null
11981209
*

‎lib/helper/Puppeteer.js‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,7 @@ import Console from './extras/Console.js'
4545
import { highlightElement } from './scripts/highlightElement.js'
4646
import { blurElement } from './scripts/blurElement.js'
4747
import { dropFile } from './scripts/dropFile.js'
48+
import { waitForChange } from './scripts/waitForChange.js'
4849
import { dontSeeElementError, seeElementError, dontSeeElementInDOMError, seeElementInDOMError } from './errors/ElementAssertion.js'
4950
import { dontSeeTraffic, seeTraffic, grabRecordedNetworkTraffics, stopRecordingTraffic, flushNetworkTraffics } from './network/actions.js'
5051
import WebElement from '../element/WebElement.js'
@@ -639,6 +640,16 @@ class Puppeteer extends Helper {
639640
return this.executeScript(() => window.location.href)
640641
}
641642

643+
async _waitForChange(ms) {
644+
const change = this.page.evaluate(waitForChange, ms).catch(() => {})
645+
let timer
646+
const wait = new Promise(resolve => {
647+
timer = setTimeout(resolve, ms)
648+
})
649+
await Promise.race([wait, change])
650+
clearTimeout(timer)
651+
}
652+
642653
/**
643654
* Grab the text within the popup. If no popup is visible then it will return null
644655
*

‎lib/helper/WebDriver.js‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,7 @@ import { focusElement } from './scripts/focusElement.js'
4141
import { blurElement } from './scripts/blurElement.js'
4242
import { dontSeeElementError, seeElementError, seeElementInDOMError, dontSeeElementInDOMError } from './errors/ElementAssertion.js'
4343
import { dropFile } from './scripts/dropFile.js'
44+
import { waitForChange } from './scripts/waitForChange.js'
4445
import { dontSeeTraffic, seeTraffic, grabRecordedNetworkTraffics, stopRecordingTraffic, flushNetworkTraffics } from './network/actions.js'
4546
import WebElement from '../element/WebElement.js'
4647
import { selectElement } from './extras/elementSelection.js'
@@ -1739,6 +1740,19 @@ class WebDriver extends Helper {
17391740
return res
17401741
}
17411742

1743+
async _waitForChange(ms) {
1744+
let timer
1745+
const wait = new Promise(resolve => {
1746+
timer = setTimeout(resolve, ms)
1747+
})
1748+
const change = this.browser.executeAsync(`(${waitForChange})(arguments[0]).then(arguments[arguments.length - 1])`, ms).catch(err => {
1749+
if (/unload|navigat|detached|stale|destroyed|realm/i.test(err.message)) return
1750+
return wait
1751+
})
1752+
await Promise.race([wait, change])
1753+
clearTimeout(timer)
1754+
}
1755+
17421756
/**
17431757
* {{> dontSeeInSource }}
17441758
*/
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
export const waitForChange = ms =>
2+
new Promise(resolve => {
3+
const observer = new MutationObserver(() => {
4+
observer.disconnect()
5+
resolve()
6+
})
7+
observer.observe(document, { subtree: true, childList: true, attributes: true, characterData: true })
8+
setTimeout(() => {
9+
observer.disconnect()
10+
resolve()
11+
}, ms)
12+
})

‎lib/plugin/retryFailedStep.js‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import debugModule from 'debug'
2+
import Container from '../container.js'
23
import event from '../event.js'
34
import recorder from '../recorder.js'
45
import store from '../store.js'
@@ -14,6 +15,7 @@ const defaultConfig = {
1415
randomize: false,
1516
ignoredSteps: [],
1617
deferToScenarioRetries: true,
18+
wakeOnChange: false,
1719
}
1820

1921
const RETRY_PRIORITIES = {
@@ -62,6 +64,7 @@ const RETRY_PRIORITIES = {
6264
* You can use step names or step prefixes ending with `*`. As such, `wait*` will match all steps starting with `wait`.
6365
* To append your own steps to ignore list - copy and paste a default steps list. Regexp values are accepted as well.
6466
* * `deferToScenarioRetries` - when enabled (default), step retries are automatically disabled if scenario retries are configured to avoid excessive total retries.
67+
* * `wakeOnChange` - when enabled, a failed step is retried as soon as the page changes (DOM mutation or navigation) instead of sleeping through the whole backoff. The backoff delay is still the upper bound. Default is false.
6568
*
6669
* #### Example
6770
*
@@ -77,6 +80,17 @@ const RETRY_PRIORITIES = {
7780
* }
7881
* ```
7982
*
83+
* Retry as soon as the page changes:
84+
*
85+
* ```js
86+
* plugins: {
87+
* retryFailedStep: {
88+
* enabled: true,
89+
* wakeOnChange: true,
90+
* }
91+
* }
92+
* ```
93+
*
8094
* #### Disable Per Test
8195
*
8296
* This plugin can be disabled per test. In this case you will need to add `step.retry()` to all flaky steps:
@@ -105,6 +119,15 @@ export default function (config) {
105119
}
106120
config.when = when
107121

122+
if (config.wakeOnChange) {
123+
config.beforeRetry = async number => {
124+
const delay = Math.min(config.minTimeout * config.factor ** (number - 2), config.maxTimeout)
125+
const helper = Object.values(Container.helpers()).find(h => typeof h._waitForChange === 'function')
126+
if (helper) return helper._waitForChange(delay)
127+
return new Promise(resolve => setTimeout(resolve, delay))
128+
}
129+
}
130+
108131
if (!recorder.retries.find(r => r === config)) {
109132
recorder.retries.push(config)
110133
}

‎lib/recorder.js‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -236,8 +236,15 @@ export default {
236236
if (!retryOpts) throw firstErr
237237
debug(`${currentQueue()} Retry opts`, JSON.stringify(retryOpts))
238238

239-
return promiseRetry(Object.assign({}, defaultRetryOptions, retryOpts), (retry, number) => {
239+
const promiseRetryOpts = Object.assign({}, defaultRetryOptions, retryOpts)
240+
if (retryOpts.beforeRetry) {
241+
promiseRetryOpts.minTimeout = 0
242+
promiseRetryOpts.maxTimeout = 0
243+
}
244+
245+
return promiseRetry(promiseRetryOpts, async (retry, number) => {
240246
if (number === 1) return retry(firstErr)
247+
if (retryOpts.beforeRetry) await retryOpts.beforeRetry(number)
241248
output.log(`${currentQueue()}Retrying... Attempt #${number}`)
242249
return runTask().catch(err => {
243250
if (ignoredErrs.includes(err)) return

‎test/helper/webapi.js‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -113,6 +113,38 @@ export function tests() {
113113
})
114114
})
115115

116+
describe('#_waitForChange', () => {
117+
it('should resolve soon after the DOM changes', async () => {
118+
await I.amOnPage('/')
119+
await I.executeScript(() => {
120+
setTimeout(() => document.body.appendChild(document.createElement('div')), 30)
121+
})
122+
const start = Date.now()
123+
await I._waitForChange(2000)
124+
expect(Date.now() - start).to.be.lessThan(500)
125+
})
126+
127+
it('should resolve after the timeout on an idle page', async () => {
128+
await I.amOnPage('/')
129+
const start = Date.now()
130+
await I._waitForChange(300)
131+
const elapsed = Date.now() - start
132+
expect(elapsed).to.be.at.least(290)
133+
expect(elapsed).to.be.lessThan(1000)
134+
})
135+
136+
it('should resolve on navigation', async function () {
137+
if (isHelper('Obscura')) this.skip() // on Obscura a script-triggered navigation neither rejects the pending Runtime.evaluate nor mutates the observed document, so the wait runs to its timeout (verified on CI: 3000ms of 3000ms)
138+
await I.amOnPage('/')
139+
await I.executeScript(() => {
140+
setTimeout(() => (window.location.href = '/info'), 30)
141+
})
142+
const start = Date.now()
143+
await I._waitForChange(3000)
144+
expect(Date.now() - start).to.be.lessThan(1500)
145+
})
146+
})
147+
116148
describe('current url : #seeInCurrentUrl, #seeCurrentUrlEquals, #grabCurrentUrl, ...', () => {
117149
it('should check for url fragment', async () => {
118150
await I.amOnPage('/form/checkbox')

0 commit comments

Comments
 (0)