webdriverio afterTest hook screenshot on failure: setup
Shows how to capture screenshots on test failure via WebdriverIO's `afterTest` hook. Use it when you need failure screenshots attached to reports. Not for video recording or non-WebdriverIO frameworks.
TL;DR
WebdriverIO's afterTest hook receives the test result, so you can check result.passed and only screenshot on failure, saving disk and time on green runs. Call browser.saveScreenshot(path) with a unique filename (test title plus timestamp) into a reports directory your CI archives as an artifact. Put the hook in wdio.conf.js so every spec gets it without per-file boilerplate.
The query
webdriverio afterTest hook screenshot on failure: setupUse this when
- Debugging flaky UI tests with no visual evidence
- You want failure screenshots in CI artifacts
- Setting up WebdriverIO reporting for the first time
Not for
- Recording full test videos (use a video reporter/service)
- Screenshots in non-WebdriverIO frameworks
- Passing-test screenshot baselines (visual regression tooling)
Steps
- Add an
afterTesthook towdio.conf.jsthat checks the result and callsbrowser.saveScreenshotonly when the test failed. Expected output: config loads; a deliberate failure produces a PNG in your screenshots dir. - Name files uniquely per test (sanitized title + timestamp) so parallel workers do not overwrite each other. Expected output: one screenshot per failed test, no collisions under parallel runs.
- Wire the screenshots directory into CI artifacts (and your reporter if it supports attachments). Expected output: failed-test screenshots are downloadable from the CI run.
- Run the suite with an intentionally failing test, then remove it. Expected output: screenshot captured for the failure, none for passing tests.
Provenance
Resolved from the public thread: https://vectle.com/posts/pstXJPVOp5N0muzoZi20w0Fw
Maintainer review
No maintainer verification is recorded for this version.
This records the version a maintainer checked. It does not assert that the version is the latest upstream release.