MCPcopy
hub / github.com/codeceptjs/CodeceptJS / takeScreenshot

Function takeScreenshot

lib/plugin/screenshot.js:191–252  ·  view source on GitHub ↗
(test, fileName, options)

Source from the content-addressed store, hash-verified

189}
190
191async function takeScreenshot(test, fileName, options) {
192 const quietMode = !store.outputDir
193 if (!quietMode) {
194 output.plugin('screenshot', `Saving screenshot ${fileName}`)
195 }
196
197 const helper = getBrowserHelper()
198 if (!helper || typeof helper.saveScreenshot !== 'function') return
199
200 try {
201 if (options.reportDir) {
202 fileName = path.join(options.reportDir, fileName)
203 const mochaReportDir = path.resolve(process.cwd(), options.reportDir)
204 if (!fileExists(mochaReportDir)) fs.mkdirSync(mochaReportDir)
205 }
206
207 if (helper.page && helper.page.isClosed && helper.page.isClosed()) {
208 throw new Error('Browser page has been closed')
209 }
210 if (helper.browser && helper.browser.isConnected && !helper.browser.isConnected()) {
211 throw new Error('Browser has been disconnected')
212 }
213
214 const screenshotPromise = helper.saveScreenshot(fileName, options.fullPageScreenshots)
215 const timeoutPromise = new Promise((_, reject) => {
216 setTimeout(() => reject(new Error('Screenshot timeout after 5 seconds')), 5000)
217 })
218
219 await Promise.race([screenshotPromise, timeoutPromise])
220
221 if (!test.artifacts) test.artifacts = {}
222 const baseOutputDir = store.outputDir || null
223 if (baseOutputDir) {
224 test.artifacts.screenshot = path.join(baseOutputDir, fileName)
225 const mocha = Container.mocha()
226 const junit = mocha?.options?.reporterOptions?.['mocha-junit-reporter']
227 if (junit?.options?.attachments) {
228 test.attachments = [path.join(baseOutputDir, fileName)]
229 }
230 } else {
231 test.artifacts.screenshot = fileName
232 }
233 } catch (err) {
234 if (!quietMode) {
235 output.plugin('screenshot', `Failed to save screenshot: ${err.message}`)
236 }
237 if (
238 err
239 && ((err.message
240 && (err.message.includes('Target page, context or browser has been closed')
241 || err.message.includes('Browser page has been closed')
242 || err.message.includes('Browser has been disconnected')
243 || err.message.includes('was terminated due to')
244 || err.message.includes('no such window: target window already closed')
245 || err.message.includes('Screenshot timeout after')))
246 || (err.type && err.type === 'RuntimeError'))
247 ) {
248 output.log(`Can't make screenshot, ${err.message}`)

Callers 2

wireOnUrlFunction · 0.85
scheduleScreenshotFunction · 0.85

Calls 6

getBrowserHelperFunction · 0.90
fileExistsFunction · 0.90
mochaMethod · 0.80
includesMethod · 0.80
logMethod · 0.80
saveScreenshotMethod · 0.45

Tested by

no test coverage detected