Skip to content

Commit 930c66d

Browse files
authored
Capture a cucumber scenario's last page before the user's After hooks run (#635)
* Capture a cucumber scenario's last page before the user's After hooks run Cucumber runs the user's After hooks before the service's afterScenario, so the end-of-scenario capture ran after a hook had ended or reloaded the session. The example's reloadSession left the last action and every assertion after it showing a blank about:blank page, and a failing scenario had no picture of its failure. The capture now runs in afterStep at the scenario's last step, or at a failed one, while the scenario's session is still alive. A test whose session a hook replaced takes no end-of-test capture from the new session. Closes #631 * Skip a final capture only when the last action's session was replaced Comparing with the session a test started on skipped a valid capture when a test reloaded and carried on, and the worker-end pass in after() still captured a blank page when the last test's afterEach reloaded. The service now records the session each action ran on, and every end-of-test capture, at test end and at worker end, is skipped only when the browser's session is no longer that one. * Check the final capture against the session of the action it captures The final capture is of the test's last page-changing action, but the session it was checked against was the last action's of any kind, so a read on a reloaded session let a click from the session before be captured on the new blank page. The service now keeps the session of the last page-changing action beside the last action's, and checks the one belonging to the action the capture is of.
1 parent 1b40109 commit 930c66d

4 files changed

Lines changed: 196 additions & 11 deletions

File tree

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'@wdio/devtools-service': patch
3+
---
4+
5+
Capture the page a cucumber scenario ended on at its last step, or at the step that failed, before the user's `After` hooks run. A hook that ended or reloaded the session left the scenario's last action and assertions showing a blank `about:blank` page, so a failing scenario had no picture of its failure. A session that a hook replaced after a test's last action is never captured as that test's last page, at test end or at worker end.

‎packages/service/CLAUDE.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ WebdriverIO service plugin (`packages/service/src`): WDIO hook binding, the comm
66

77
### One DOM snapshot per action, taken before it
88

9-
In trace mode the per-action snapshot is captured in `beforeCommand`, stamped at the previous action's end, so every row resolves to a state the driver was idle for. `afterCommand` captures nothing. The last action's snapshot is supplied by `#finalizePerScenario`.
9+
In trace mode the per-action snapshot is captured in `beforeCommand`, stamped at the previous action's end, so every row resolves to a state the driver was idle for. `afterCommand` captures nothing. The last action's snapshot is supplied by `#finalizePerScenario`. In a cucumber scenario it runs in `afterStep` at the scenario's last step or a failed one, because cucumber runs the user's `After` hooks before the service's `afterScenario`, and a hook that ends or reloads the session leaves a blank page. It is skipped whenever the browser's session is no longer the one the last action ran on (a hook's `reloadSession`), at test end and at worker end alike; a test that reloads and carries on is captured on its new session.
1010

1111
`settleAfterLastAction` is gated, not timed. It waits for `document.readyState === 'complete'` only when the last action navigated to a document the session had not seen (`SessionCapturer.replacedDocumentInLastDrain`). Otherwise it returns at once. Native pauses 250 ms instead.
1212
Don't add an eager post-action capture, a `readyState` poll without that gate, or a document tag: the outgoing document already reports `complete` right after a click, so an ungated poll captures the page the test just left.

‎packages/service/src/index.ts‎

Lines changed: 47 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -186,6 +186,9 @@ export default class DevToolsHookService implements Services.ServiceInstance {
186186
/** Wall-clock ms at the current test's start, set in beforeTest/beforeScenario;
187187
* the lower bound of that test's video frame window (per-test slicing). */
188188
#currentTestStartWallTime = 0
189+
/** The sessions the last action and the last page-changing action ran on, for the final capture to check against whichever of the two it captures: a session that replaced it since (a hook's `reloadSession`) holds no page of that action. */
190+
#lastActionSessionId?: string
191+
#lastChangeSessionId?: string
189192
#awaitingInitialCapture = true
190193
#initialCaptureAttempts = 0
191194

@@ -512,13 +515,22 @@ export default class DevToolsHookService implements Services.ServiceInstance {
512515
// afterStep fires right after each step, so the failing assertion lands next
513516
// to the step's actions rather than after reloadSession at scenario end.
514517
async afterStep(
515-
_step?: unknown,
516-
_scenario?: unknown,
517-
result?: { error?: unknown }
518+
step?: { id?: string },
519+
scenario?: { steps?: readonly { id?: string }[] },
520+
result?: { error?: unknown; passed?: boolean }
518521
) {
519522
await this.#closeOpenWaits(result?.error, Date.now())
520523
this.#currentStepUid = undefined
521524
this.#assertionTracker.handleOutcome(result?.error)
525+
// Cucumber runs AfterStep hooks before the user's After hooks, which can end
526+
// or reload the session, so the page the scenario ended on is captured here:
527+
// at its last step, or at a failed one, after which the rest are skipped.
528+
const steps = scenario?.steps
529+
const lastStep =
530+
step?.id !== undefined && steps?.[steps.length - 1]?.id === step.id
531+
if (lastStep || result?.error !== undefined || result?.passed === false) {
532+
await this.#finalizePerScenario()
533+
}
522534
}
523535

524536
/** Stamp final state + the tracker's 0-based attempt onto the test's metadata
@@ -656,6 +668,15 @@ export default class DevToolsHookService implements Services.ServiceInstance {
656668
if (!capturesTrace(this.#options.mode) || !this.#browser) {
657669
return
658670
}
671+
const { lastAction, sessionId } = this.#finalCaptureTarget()
672+
// A hook that reloaded or ended the session after that action (an After or
673+
// afterEach hook's reloadSession) leaves a blank page in its place.
674+
if (sessionId !== undefined && this.#browser.sessionId !== sessionId) {
675+
log.info(
676+
'The session was replaced after the last action, so its page is not captured again'
677+
)
678+
return
679+
}
659680
// Drain the collector one final time while the session is still alive, so the
660681
// DOM the LAST command produced is recorded — a closing navigation (e.g. a
661682
// logout landing back on the login page) fires no subsequent beforeCommand,
@@ -669,13 +690,6 @@ export default class DevToolsHookService implements Services.ServiceInstance {
669690
// action's has no successor and this is the only capture of it. A session
670691
// that ran no action names it FINAL_SNAPSHOT_COMMAND, which the per-test
671692
// screenshot reads as "post-teardown frame, do not use".
672-
const lastChange = this.#lastCommandWhere(
673-
(command) => !skipsCapture(command)
674-
)
675-
const lastAction =
676-
lastChange && lastChange.timestamp >= this.#currentTestStartWallTime
677-
? lastChange
678-
: this.#lastAction()
679693
// A session with no action has no timestamp of its own to key on, so its
680694
// frame is recognised by the marker instead — otherwise `Date.now()` differs
681695
// between the per-test finalize and `after()` and both capture.
@@ -717,6 +731,23 @@ export default class DevToolsHookService implements Services.ServiceInstance {
717731
}
718732
}
719733

734+
/** The action the final capture is of, and the session it ran on: the test's last page-changing action, or its last action of any kind when it changed no page. */
735+
#finalCaptureTarget(): {
736+
lastAction?: { command: string; timestamp: number }
737+
sessionId?: string
738+
} {
739+
const lastChange = this.#lastCommandWhere(
740+
(command) => !skipsCapture(command)
741+
)
742+
if (lastChange && lastChange.timestamp >= this.#currentTestStartWallTime) {
743+
return { lastAction: lastChange, sessionId: this.#lastChangeSessionId }
744+
}
745+
return {
746+
lastAction: this.#lastAction(),
747+
sessionId: this.#lastActionSessionId
748+
}
749+
}
750+
720751
/** A command a snapshot can be attributed to: mapped (so it has a row to
721752
* render on) and not internal (several of those ARE mapped — getTitle,
722753
* getUrl, execute — and a snapshot stamped at one would sit at a timestamp
@@ -996,6 +1027,12 @@ export default class DevToolsHookService implements Services.ServiceInstance {
9961027
this.#currentStepUid,
9971028
nesting
9981029
)
1030+
if (this.#isActionCommand(command)) {
1031+
this.#lastActionSessionId = this.#browser.sessionId
1032+
if (!skipsCapture(command)) {
1033+
this.#lastChangeSessionId = this.#browser.sessionId
1034+
}
1035+
}
9991036
// Trace mode captures nothing here: the state this action produced is
10001037
// taken by the NEXT action's pre-capture, when the app has settled.
10011038
if (startsBackend(this.#options.mode)) {

‎packages/service/tests/trace-action-capture.test.ts‎

Lines changed: 143 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@ const capturer = {
4040
resetRetryTracker: vi.fn(),
4141
captureSource: vi.fn(),
4242
captureAssertCommand: vi.fn(),
43+
failLastAction: vi.fn(),
4344
cleanup: vi.fn(),
4445
commandsLog,
4546
sources: new Map(),
@@ -494,6 +495,148 @@ describe('trace mode: one capture per action, taken before it', () => {
494495
])
495496
})
496497

498+
describe('a cucumber scenario whose After hook replaces the session', () => {
499+
const pickle = {
500+
uri: 'features/login.feature',
501+
name: 'logs in',
502+
steps: [{ id: 'step-1' }, { id: 'step-2' }]
503+
}
504+
505+
async function scenarioUpToItsLastStep(result: {
506+
passed: boolean
507+
error?: unknown
508+
}) {
509+
const browser = nativeBrowser()
510+
const service = new DevToolsHookService({ mode: 'trace' })
511+
await service.before({} as never, [], browser)
512+
service.beforeScenario({ pickle })
513+
clock = Date.now() + 1000
514+
service.beforeStep({ text: 'I fill the form' })
515+
await service.beforeCommand('setValue' as never, [])
516+
await service.afterCommand('setValue' as never, [], undefined)
517+
await service.afterStep({ id: 'step-1' }, pickle, { passed: true })
518+
service.beforeStep({ text: 'I submit it' })
519+
await service.beforeCommand('click' as never, [])
520+
await service.afterCommand('click' as never, [], undefined)
521+
vi.mocked(captureActionSnapshot).mockClear()
522+
await service.afterStep(
523+
{ id: result.passed ? 'step-2' : 'step-1' },
524+
pickle,
525+
result
526+
)
527+
return { browser, service }
528+
}
529+
530+
it('captures the page the scenario ended on at its last step, before the After hooks run', async () => {
531+
const { browser, service } = await scenarioUpToItsLastStep({
532+
passed: true
533+
})
534+
expect(vi.mocked(captureActionSnapshot)).toHaveBeenCalledTimes(1)
535+
expect(namedAt(0)).toBe('click')
536+
537+
// The example's After hook: browser.reloadSession() gives the browser a new, blank session.
538+
;(browser as { sessionId: string }).sessionId = 'reloaded-session'
539+
await service.afterScenario({ pickle }, { passed: true })
540+
expect(vi.mocked(captureActionSnapshot)).toHaveBeenCalledTimes(1)
541+
})
542+
543+
it('captures at a failed step, after which cucumber skips the rest', async () => {
544+
await scenarioUpToItsLastStep({
545+
passed: false,
546+
error: new Error('flash text did not match')
547+
})
548+
expect(vi.mocked(captureActionSnapshot)).toHaveBeenCalledTimes(1)
549+
expect(namedAt(0)).toBe('click')
550+
})
551+
552+
it('does not capture the end of the scenario at a step before its last', async () => {
553+
const browser = nativeBrowser()
554+
const service = new DevToolsHookService({ mode: 'trace' })
555+
await service.before({} as never, [], browser)
556+
service.beforeScenario({ pickle })
557+
service.beforeStep({ text: 'I fill the form' })
558+
await service.beforeCommand('setValue' as never, [])
559+
await service.afterCommand('setValue' as never, [], undefined)
560+
vi.mocked(captureActionSnapshot).mockClear()
561+
await service.afterStep({ id: 'step-1' }, pickle, { passed: true })
562+
expect(vi.mocked(captureActionSnapshot)).not.toHaveBeenCalled()
563+
})
564+
})
565+
566+
it('takes no end-of-test capture from a session a hook replaced', async () => {
567+
const browser = nativeBrowser()
568+
const service = new DevToolsHookService({ mode: 'trace' })
569+
await service.before({} as never, [], browser)
570+
const test = { file: '/spec/a.ts', title: 'submit' }
571+
service.beforeTest(test as never)
572+
await service.beforeCommand('click' as never, [])
573+
await service.afterCommand('click' as never, [], undefined)
574+
575+
// A mocha afterEach that reloads the session runs before the service's afterTest.
576+
;(browser as { sessionId: string }).sessionId = 'reloaded-session'
577+
vi.mocked(captureActionSnapshot).mockClear()
578+
await service.afterTest(test as never, {} as never, {} as never)
579+
580+
expect(vi.mocked(captureActionSnapshot)).not.toHaveBeenCalled()
581+
})
582+
583+
it('captures the last action of a test that reloaded its session and carried on', async () => {
584+
const browser = nativeBrowser()
585+
const service = new DevToolsHookService({ mode: 'trace' })
586+
await service.before({} as never, [], browser)
587+
const test = { file: '/spec/a.ts', title: 'reload then submit' }
588+
service.beforeTest(test as never)
589+
await service.beforeCommand('click' as never, [])
590+
await service.afterCommand('click' as never, [], undefined)
591+
592+
;(browser as { sessionId: string }).sessionId = 'reloaded-session'
593+
clock = Date.now() + 1000
594+
await service.beforeCommand('click' as never, [])
595+
await service.afterCommand('click' as never, [], undefined)
596+
vi.mocked(captureActionSnapshot).mockClear()
597+
await service.afterTest(test as never, {} as never, {} as never)
598+
599+
expect(vi.mocked(captureActionSnapshot)).toHaveBeenCalledTimes(1)
600+
expect(stampedAt(0)).toBe(commandsLog.at(-1)!.timestamp)
601+
})
602+
603+
it('takes no capture of a click on a session a later read ran after a reload', async () => {
604+
const browser = nativeBrowser()
605+
const service = new DevToolsHookService({ mode: 'trace' })
606+
await service.before({} as never, [], browser)
607+
const test = { file: '/spec/a.ts', title: 'click, reload, read' }
608+
service.beforeTest(test as never)
609+
clock = Date.now() + 1000
610+
await service.beforeCommand('click' as never, [])
611+
await service.afterCommand('click' as never, [], undefined)
612+
613+
;(browser as { sessionId: string }).sessionId = 'reloaded-session'
614+
await service.beforeCommand('getTitle' as never, [])
615+
await service.afterCommand('getTitle' as never, [], undefined)
616+
vi.mocked(captureActionSnapshot).mockClear()
617+
await service.afterTest(test as never, {} as never, {} as never)
618+
619+
// The capture would be of the click, whose page the reloaded session no longer holds.
620+
expect(vi.mocked(captureActionSnapshot)).not.toHaveBeenCalled()
621+
})
622+
623+
it('takes no capture at worker end from a session the last test reloaded', async () => {
624+
const browser = nativeBrowser()
625+
const service = new DevToolsHookService({ mode: 'trace' })
626+
await service.before({} as never, [], browser)
627+
const test = { file: '/spec/a.ts', title: 'submit' }
628+
service.beforeTest(test as never)
629+
await service.beforeCommand('click' as never, [])
630+
await service.afterCommand('click' as never, [], undefined)
631+
632+
;(browser as { sessionId: string }).sessionId = 'reloaded-session'
633+
await service.afterTest(test as never, {} as never, {} as never)
634+
vi.mocked(captureActionSnapshot).mockClear()
635+
await service.after()
636+
637+
expect(vi.mocked(captureActionSnapshot)).not.toHaveBeenCalled()
638+
})
639+
497640
it('stamps the final capture at the test last page change, past later reads', async () => {
498641
const browser = nativeBrowser()
499642
const service = new DevToolsHookService({ mode: 'trace' })

0 commit comments

Comments
 (0)