-
-
Notifications
You must be signed in to change notification settings - Fork 752
Expand file tree
/
Copy pathscreenshotOnFail.js
More file actions
179 lines (155 loc) · 6.25 KB
/
Copy pathscreenshotOnFail.js
File metadata and controls
179 lines (155 loc) · 6.25 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
import fs from 'fs'
import path from 'path'
import Container from '../container.js'
import recorder from '../recorder.js'
import event from '../event.js'
import output from '../output.js'
import { fileExists } from '../utils.js'
import Codeceptjs from '../index.js'
import { testToFileName } from '../mocha/test.js'
const defaultConfig = {
uniqueScreenshotNames: false,
disableScreenshots: false,
fullPageScreenshots: false,
runInParent: false,
}
const supportedHelpers = Container.STANDARD_ACTING_HELPERS
/**
* Creates screenshot on failure. Screenshot is saved into `output` directory.
*
* Initially this functionality was part of corresponding helper but has been moved into plugin since 1.4
*
* This plugin is **enabled by default**.
*
* #### Configuration
*
* Configuration can either be taken from a corresponding helper (deprecated) or a from plugin config (recommended).
*
* ```js
* plugins: {
* screenshotOnFail: {
* enabled: true
* }
* }
* ```
*
* Possible config options:
*
* * `uniqueScreenshotNames`: use unique names for screenshot. Default: false.
* * `fullPageScreenshots`: make full page screenshots. Default: false.
*
*
*/
export default function (config) {
const helpers = Container.helpers()
let helper
for (const helperName of supportedHelpers) {
if (Object.keys(helpers).indexOf(helperName) > -1) {
helper = helpers[helperName]
}
}
if (!helper) return // no helpers for screenshot
const options = Object.assign(defaultConfig, helper.options, config)
if (helpers.Mochawesome) {
if (helpers.Mochawesome.config) {
options.uniqueScreenshotNames = helpers.Mochawesome.config.uniqueScreenshotNames
}
}
if (Codeceptjs.container.mocha()) {
options.reportDir = Codeceptjs.container.mocha()?.options?.reporterOptions && Codeceptjs.container.mocha()?.options?.reporterOptions?.reportDir
}
if (options.disableScreenshots) {
// old version of disabling screenshots
return
}
event.dispatcher.on(event.test.failed, (test, _err, hookName) => {
if (hookName === 'BeforeSuite' || hookName === 'AfterSuite') {
// no browser here
return
}
recorder.add(
'screenshot of failed test',
async () => {
const dataType = 'image/png'
// This prevents data driven to be included in the failed screenshot file name
let fileName
if (options.uniqueScreenshotNames && test) {
fileName = `${testToFileName(test, { suffix: '', unique: true })}.failed.png`
} else {
fileName = `${testToFileName(test, { suffix: '', unique: false })}.failed.png`
}
const quietMode = !('output_dir' in global) || !global.output_dir
if (!quietMode) {
output.plugin('screenshotOnFail', 'Test failed, try to save a screenshot')
}
// Re-check helpers at runtime in case they weren't ready during plugin init
const runtimeHelpers = Container.helpers()
let runtimeHelper = null
for (const helperName of supportedHelpers) {
if (Object.keys(runtimeHelpers).indexOf(helperName) > -1) {
runtimeHelper = runtimeHelpers[helperName]
break
}
}
if (runtimeHelper && typeof runtimeHelper.saveScreenshot === 'function') {
helper = runtimeHelper
}
try {
if (options.reportDir) {
fileName = path.join(options.reportDir, fileName)
const mochaReportDir = path.resolve(process.cwd(), options.reportDir)
if (!fileExists(mochaReportDir)) {
fs.mkdirSync(mochaReportDir)
}
}
// Check if browser/page is still available before attempting screenshot
if (helper.page && helper.page.isClosed && helper.page.isClosed()) {
throw new Error('Browser page has been closed')
}
if (helper.browser && helper.browser.isConnected && !helper.browser.isConnected()) {
throw new Error('Browser has been disconnected')
}
// Add timeout wrapper to prevent hanging with shorter timeout for ESM
const screenshotPromise = helper.saveScreenshot(fileName, options.fullPageScreenshots)
const timeoutPromise = new Promise((_, reject) => {
setTimeout(() => reject(new Error('Screenshot timeout after 5 seconds')), 5000)
})
await Promise.race([screenshotPromise, timeoutPromise])
if (!test.artifacts) test.artifacts = {}
// Some unit tests may not define global.output_dir; avoid throwing when it is undefined
// Detect output directory safely (may not be initialized in narrow unit tests)
const baseOutputDir = 'output_dir' in global && typeof global.output_dir === 'string' && global.output_dir ? global.output_dir : null
if (baseOutputDir) {
test.artifacts.screenshot = path.join(baseOutputDir, fileName)
if (Container.mocha().options.reporterOptions['mocha-junit-reporter'] && Container.mocha().options.reporterOptions['mocha-junit-reporter'].options.attachments) {
test.attachments = [path.join(baseOutputDir, fileName)]
}
} else {
// Fallback: just store the file name to keep tests stable without triggering path errors
test.artifacts.screenshot = fileName
}
} catch (err) {
if (!quietMode) {
output.plugin('screenshotOnFail', `Failed to save screenshot: ${err.message}`)
}
// Enhanced error handling for browser closed scenarios
if (
err &&
((err.message &&
(err.message.includes('Target page, context or browser has been closed') ||
err.message.includes('Browser page has been closed') ||
err.message.includes('Browser has been disconnected') ||
err.message.includes('was terminated due to') ||
err.message.includes('no such window: target window already closed') ||
err.message.includes('Screenshot timeout after'))) ||
(err.type && err.type === 'RuntimeError'))
) {
output.log(`Can't make screenshot, ${err.message}`)
helper.isRunning = false
}
}
},
true,
)
})
}