codeceptjs 3.7.0-beta.7 → 3.7.0-beta.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/lib/actor.js +1 -2
  2. package/lib/ai.js +130 -121
  3. package/lib/codecept.js +4 -4
  4. package/lib/command/check.js +4 -0
  5. package/lib/command/run-workers.js +1 -53
  6. package/lib/command/workers/runTests.js +25 -189
  7. package/lib/container.js +16 -0
  8. package/lib/els.js +87 -106
  9. package/lib/event.js +18 -17
  10. package/lib/helper/Playwright.js +7 -1
  11. package/lib/listener/exit.js +5 -8
  12. package/lib/listener/globalTimeout.js +26 -9
  13. package/lib/listener/result.js +12 -0
  14. package/lib/listener/steps.js +0 -6
  15. package/lib/listener/store.js +9 -1
  16. package/lib/mocha/asyncWrapper.js +12 -2
  17. package/lib/mocha/cli.js +65 -31
  18. package/lib/mocha/hooks.js +32 -3
  19. package/lib/mocha/suite.js +27 -1
  20. package/lib/mocha/test.js +91 -7
  21. package/lib/mocha/types.d.ts +5 -0
  22. package/lib/output.js +2 -1
  23. package/lib/plugin/analyze.js +348 -0
  24. package/lib/plugin/commentStep.js +5 -0
  25. package/lib/plugin/customReporter.js +52 -0
  26. package/lib/plugin/heal.js +2 -2
  27. package/lib/plugin/pageInfo.js +140 -0
  28. package/lib/plugin/retryTo.js +10 -2
  29. package/lib/plugin/screenshotOnFail.js +11 -16
  30. package/lib/plugin/stepByStepReport.js +5 -4
  31. package/lib/plugin/stepTimeout.js +1 -1
  32. package/lib/plugin/tryTo.js +9 -1
  33. package/lib/recorder.js +4 -4
  34. package/lib/rerun.js +43 -42
  35. package/lib/result.js +161 -0
  36. package/lib/step/base.js +52 -4
  37. package/lib/step/func.js +46 -0
  38. package/lib/step/helper.js +3 -0
  39. package/lib/step/meta.js +9 -1
  40. package/lib/step/record.js +5 -5
  41. package/lib/step/section.js +55 -0
  42. package/lib/step.js +6 -0
  43. package/lib/steps.js +28 -1
  44. package/lib/store.js +2 -0
  45. package/lib/{step/timeout.js → timeout.js} +24 -0
  46. package/lib/utils.js +35 -0
  47. package/lib/workers.js +28 -38
  48. package/package.json +7 -6
  49. package/typings/promiseBasedTypes.d.ts +104 -0
  50. package/typings/types.d.ts +104 -0
  51. package/lib/listener/artifacts.js +0 -19
  52. package/lib/plugin/debugErrors.js +0 -67
@@ -0,0 +1,348 @@
1
+ const debug = require('debug')('codeceptjs:analyze')
2
+ const { isMainThread } = require('node:worker_threads')
3
+ const { arrowRight } = require('figures')
4
+ const container = require('../container')
5
+ const store = require('../store')
6
+ const ai = require('../ai')
7
+ const colors = require('chalk')
8
+ const ora = require('ora-classic')
9
+ const event = require('../event')
10
+ const output = require('../output')
11
+ const { ansiRegExp, base64EncodeFile, markdownToAnsi } = require('../utils')
12
+
13
+ const MAX_DATA_LENGTH = 5000
14
+
15
+ const defaultConfig = {
16
+ clusterize: 5,
17
+ analyze: 2,
18
+ vision: false,
19
+ categories: [
20
+ 'Browser connection error / browser crash',
21
+ 'Network errors (server error, timeout, etc)',
22
+ 'HTML / page elements (not found, not visible, etc)',
23
+ 'Navigation errors (404, etc)',
24
+ 'Code errors (syntax error, JS errors, etc)',
25
+ 'Library & framework errors (CodeceptJS internal errors, user-defined libraries, etc)',
26
+ 'Data errors (password incorrect, no options in select, invalid format, etc)',
27
+ 'Assertion failures',
28
+ 'Other errors',
29
+ ],
30
+ prompts: {
31
+ clusterize: (tests, config) => {
32
+ const serializedFailedTests = tests
33
+ .map((test, index) => {
34
+ if (!test || !test.err) return
35
+ return `
36
+ #${index + 1}: ${serializeTest(test)}
37
+ ${serializeError(test.err).slice(0, MAX_DATA_LENGTH / tests.length)}`.trim()
38
+ })
39
+ .join('\n\n--------\n\n')
40
+
41
+ const messages = [
42
+ {
43
+ role: 'user',
44
+ content: `
45
+ I am test analyst analyzing failed tests in CodeceptJS testing framework.
46
+
47
+ Please analyze the following failed tests and classify them into groups by their cause.
48
+ If there is no groups detected, say: "No common groups found".
49
+
50
+ Provide a short description of the group and a list of failed tests that belong to this group.
51
+ Use percent sign to indicate the percentage of failed tests in the group if this percentage is greater than 30%.
52
+
53
+ Here are failed tests:
54
+
55
+ ${serializedFailedTests}
56
+
57
+ Common categories of failures by order of priority:
58
+
59
+ ${config.categories.join('\n- ')}
60
+
61
+ If there is no groups of tests, say: "No patterns found"
62
+ Preserve error messages but cut them if they are too long.
63
+ Respond clearly and directly, without introductory words or phrases like ‘Of course,’ ‘Here is the answer,’ etc.
64
+ Do not list more than 3 errors in the group.
65
+ If you identify that all tests in the group have the same tag, add this tag to the group report, otherwise ignore TAG section.
66
+ If you identify that all tests in the group have the same suite, add this suite to the group report, otherwise ignore SUITE section.
67
+ Pick different emojis for each group.
68
+ Order groups by the number of tests in the group.
69
+ If group has one test, skip that group.
70
+
71
+ Provide list of groups in following format:
72
+
73
+ _______________________________
74
+
75
+ ## Group <group_number> <emoji>
76
+
77
+ * SUMMARY <summary_of_errors>
78
+ * CATEGORY <category_of_failure>
79
+ * URL <url_of_failure_if_any>
80
+ * ERROR <error_message_1>, <error_message_2>, ...
81
+ * STEP <step_of_failure> (use CodeceptJS format I.click(), I.see(), etc; if all failures happend on the same step)
82
+ * SUITE <suite_title>, <suite_title> (if SUITE is present, and if all tests in the group have the same suite or suites)
83
+ * TAG <tag> (if TAG is present, and if all tests in the group have the same tag)
84
+ * AFFECTED TESTS (<total number of tests>):
85
+ x <test1 title>
86
+ x <test2 title>
87
+ x <test3 title>
88
+ x ...
89
+ `,
90
+ },
91
+ ]
92
+ return messages
93
+ },
94
+ analyze: (test, config) => {
95
+ const testMessage = serializeTest(test)
96
+ const errorMessage = serializeError(test.err)
97
+
98
+ const messages = [
99
+ {
100
+ role: 'user',
101
+ content: [
102
+ {
103
+ type: 'text',
104
+ text: `
105
+ I am qa engineer analyzing failed tests in CodeceptJS testing framework.
106
+ Please analyze the following failed test and error its error and explain it.
107
+
108
+ Pick one of the categories of failures and explain it.
109
+
110
+ Categories of failures in order of priority:
111
+
112
+ ${config.categories.join('\n- ')}
113
+
114
+ Here is the test and error:
115
+
116
+ ------- TEST -------
117
+ ${testMessage}
118
+
119
+ ------- ERROR -------
120
+ ${errorMessage}
121
+
122
+ ------ INSTRUCTIONS ------
123
+
124
+ Do not get to details, be concise.
125
+ If there is failed step, just write it in STEPS section.
126
+ If you have suggestions for the test, write them in SUMMARY section.
127
+ Do not be too technical in SUMMARY section.
128
+ Inside SUMMARY write exact values, if you have suggestions, explain which information you used to suggest.
129
+ Be concise, each section should not take more than one sentence.
130
+
131
+ Response format:
132
+
133
+ * SUMMARY <explanation_of_failure>
134
+ * ERROR <error_message_1>, <error_message_2>, ...
135
+ * CATEGORY <category_of_failure>
136
+ * STEPS <step_of_failure>
137
+ * URL <url_of_failure_if_any>
138
+
139
+ Do not add any other sections or explanations. Only CATEGORY, SUMMARY, STEPS.
140
+ ${config.vision ? 'Also a screenshot of the page is attached to the prompt.' : ''}
141
+ `,
142
+ },
143
+ ],
144
+ },
145
+ ]
146
+
147
+ if (config.vision && test.artifacts.screenshot) {
148
+ debug('Adding screenshot to prompt')
149
+ messages[0].content.push({
150
+ type: 'image_url',
151
+ image_url: {
152
+ url: 'data:image/png;base64,' + base64EncodeFile(test.artifacts.screenshot),
153
+ },
154
+ })
155
+ }
156
+
157
+ return messages
158
+ },
159
+ },
160
+ }
161
+
162
+ /**
163
+ *
164
+ * @param {*} config
165
+ * @returns
166
+ */
167
+ module.exports = function (config = {}) {
168
+ config = Object.assign(defaultConfig, config)
169
+
170
+ event.dispatcher.on(event.workers.before, () => {
171
+ if (!ai.isEnabled) return
172
+ console.log('Enabled AI analysis')
173
+ })
174
+
175
+ event.dispatcher.on(event.all.result, async result => {
176
+ if (!isMainThread) return // run only on main thread
177
+ if (!ai.isEnabled) {
178
+ console.log('AI is disabled, no analysis will be performed. Run tests with --ai flag to enable it.')
179
+ return
180
+ }
181
+
182
+ printReport(result)
183
+ })
184
+
185
+ event.dispatcher.on(event.workers.result, async result => {
186
+ if (!result.hasFailed) {
187
+ console.log('Everything is fine, skipping AI analysis')
188
+ return
189
+ }
190
+
191
+ if (!ai.isEnabled) {
192
+ console.log('AI is disabled, no analysis will be performed. Run tests with --ai flag to enable it.')
193
+ return
194
+ }
195
+
196
+ printReport(result)
197
+ })
198
+
199
+ async function printReport(result) {
200
+ const failedTestsAndErrors = result.tests.filter(t => t.err)
201
+
202
+ if (!failedTestsAndErrors.length) return
203
+
204
+ debug(failedTestsAndErrors.map(t => serializeTest(t) + '\n' + serializeError(t.err)))
205
+
206
+ try {
207
+ if (failedTestsAndErrors.length >= config.clusterize) {
208
+ const response = await clusterize(failedTestsAndErrors)
209
+ printHeader()
210
+ console.log(response)
211
+ return
212
+ }
213
+
214
+ output.plugin('analyze', `Analyzing first ${config.analyze} failed tests...`)
215
+
216
+ // we pick only unique errors to not repeat answers
217
+ const uniqueErrors = failedTestsAndErrors.filter((item, index, array) => {
218
+ return array.findIndex(t => t.err?.message === item.err?.message) === index
219
+ })
220
+
221
+ for (let i = 0; i < config.analyze; i++) {
222
+ if (!uniqueErrors[i]) break
223
+
224
+ const response = await analyze(uniqueErrors[i])
225
+ if (!response) {
226
+ break
227
+ }
228
+
229
+ printHeader()
230
+ console.log()
231
+ console.log('--------------------------------')
232
+ console.log(arrowRight, colors.bold.white(uniqueErrors[i].fullTitle()), config.vision ? '👀' : '')
233
+ console.log()
234
+ console.log()
235
+ console.log(response)
236
+ console.log()
237
+ }
238
+ } catch (err) {
239
+ console.error('Error analyzing failed tests', err)
240
+ }
241
+
242
+ if (!Object.keys(container.plugins()).includes('pageInfo')) {
243
+ console.log('To improve analysis, enable pageInfo plugin to get more context for failed tests.')
244
+ }
245
+ }
246
+
247
+ let hasPrintedHeader = false
248
+
249
+ function printHeader() {
250
+ if (!hasPrintedHeader) {
251
+ console.log()
252
+ console.log(colors.bold.white('🪄 AI REPORT:'))
253
+ hasPrintedHeader = true
254
+ }
255
+ }
256
+
257
+ async function clusterize(failedTestsAndErrors) {
258
+ const spinner = ora('Clusterizing failures...').start()
259
+ const prompt = config.prompts.clusterize(failedTestsAndErrors, config)
260
+ try {
261
+ const response = await ai.createCompletion(prompt)
262
+ spinner.stop()
263
+ return formatResponse(response)
264
+ } catch (err) {
265
+ spinner.stop()
266
+ console.error('Error clusterizing failures', err.message)
267
+ }
268
+ }
269
+
270
+ async function analyze(failedTestAndError) {
271
+ const spinner = ora('Analyzing failure...').start()
272
+ const prompt = config.prompts.analyze(failedTestAndError, config)
273
+ try {
274
+ const response = await ai.createCompletion(prompt)
275
+ spinner.stop()
276
+ return formatResponse(response)
277
+ } catch (err) {
278
+ spinner.stop()
279
+ console.error('Error analyzing failure:', err.message)
280
+ }
281
+ }
282
+ }
283
+
284
+ function serializeError(error) {
285
+ if (typeof error === 'string') {
286
+ return error
287
+ }
288
+
289
+ if (!error) return
290
+
291
+ let errorMessage = 'ERROR: ' + error.message
292
+
293
+ if (error.inspect) {
294
+ errorMessage = 'ERROR: ' + error.inspect()
295
+ }
296
+
297
+ if (error.stack) {
298
+ errorMessage +=
299
+ '\n' +
300
+ error.stack
301
+ .replace(global.codecept_dir || '', '.')
302
+ .split('\n')
303
+ .map(line => line.replace(ansiRegExp(), ''))
304
+ .slice(0, 5)
305
+ .join('\n')
306
+ }
307
+ if (error.steps) {
308
+ errorMessage += '\n STEPS: ' + error.steps.map(s => s.toCode()).join('\n')
309
+ }
310
+ return errorMessage
311
+ }
312
+
313
+ function serializeTest(test) {
314
+ if (!test.uid) return
315
+
316
+ let testMessage = 'TEST TITLE: ' + test.title
317
+
318
+ if (test.suite) {
319
+ testMessage += '\n SUITE: ' + test.suite.title
320
+ }
321
+ if (test.parent) {
322
+ testMessage += '\n SUITE: ' + test.parent.title
323
+ }
324
+
325
+ if (test.steps?.length) {
326
+ const failedSteps = test.steps
327
+ if (failedSteps.length) testMessage += '\n STEP: ' + failedSteps.map(s => s.toCode()).join('; ')
328
+ }
329
+
330
+ const pageInfo = test.notes.find(n => n.type === 'pageInfo')
331
+ if (pageInfo) {
332
+ testMessage += '\n PAGE INFO: ' + pageInfo.text
333
+ }
334
+
335
+ return testMessage
336
+ }
337
+
338
+ function formatResponse(response) {
339
+ return response
340
+ .replace(/<think>([\s\S]*?)<\/think>/g, store.debugMode ? colors.cyan('$1') : '')
341
+ .split('\n')
342
+ .map(line => line.trim())
343
+ .filter(line => !/^[A-Z\s]+$/.test(line))
344
+ .map(line => markdownToAnsi(line))
345
+ .map(line => line.replace(/^x /gm, ` ${colors.red.bold('x')} `))
346
+ .join('\n')
347
+ .trim()
348
+ }
@@ -7,6 +7,8 @@ let currentCommentStep
7
7
  const defaultGlobalName = '__'
8
8
 
9
9
  /**
10
+ * @deprecated
11
+ *
10
12
  * Add descriptive nested steps for your tests:
11
13
  *
12
14
  * ```js
@@ -100,6 +102,9 @@ const defaultGlobalName = '__'
100
102
  * ```
101
103
  */
102
104
  module.exports = function (config) {
105
+ console.log('commentStep is deprecated, disable it and use Section instead')
106
+ console.log('const { Section: __ } = require("codeceptjs/steps")')
107
+
103
108
  event.dispatcher.on(event.test.started, () => {
104
109
  currentCommentStep = null
105
110
  })
@@ -0,0 +1,52 @@
1
+ const event = require('../event')
2
+
3
+ /**
4
+ * Sample custom reporter for CodeceptJS.
5
+ */
6
+ module.exports = function (config) {
7
+ event.dispatcher.on(event.hook.finished, hook => {
8
+ if (config.onHookFinished) {
9
+ config.onHookFinished(hook)
10
+ }
11
+ })
12
+
13
+ event.dispatcher.on(event.test.before, test => {
14
+ if (config.onTestBefore) {
15
+ config.onTestBefore(test)
16
+ }
17
+ })
18
+
19
+ event.dispatcher.on(event.test.failed, (test, err) => {
20
+ if (config.onTestFailed) {
21
+ config.onTestFailed(test, err)
22
+ }
23
+ })
24
+
25
+ event.dispatcher.on(event.test.passed, test => {
26
+ if (config.onTestPassed) {
27
+ config.onTestPassed(test)
28
+ }
29
+ })
30
+
31
+ event.dispatcher.on(event.test.skipped, test => {
32
+ if (config.onTestSkipped) {
33
+ config.onTestSkipped(test)
34
+ }
35
+ })
36
+
37
+ event.dispatcher.on(event.test.finished, test => {
38
+ if (config.onTestFinished) {
39
+ config.onTestFinished(test)
40
+ }
41
+ })
42
+
43
+ event.dispatcher.on(event.all.result, result => {
44
+ if (config.onResult) {
45
+ config.onResult(result)
46
+ }
47
+
48
+ if (config.save) {
49
+ result.save()
50
+ }
51
+ })
52
+ }
@@ -117,10 +117,10 @@ module.exports = function (config = {}) {
117
117
  }
118
118
  })
119
119
 
120
- event.dispatcher.on(event.workers.result, ({ tests }) => {
120
+ event.dispatcher.on(event.workers.result, result => {
121
121
  const { print } = output
122
122
 
123
- const healedTests = Object.values(tests)
123
+ const healedTests = Object.values(result.tests)
124
124
  .flat()
125
125
  .filter(test => test.notes.some(note => note.type === 'heal'))
126
126
  if (!healedTests.length) return
@@ -0,0 +1,140 @@
1
+ const path = require('path')
2
+ const fs = require('fs')
3
+ const Container = require('../container')
4
+ const recorder = require('../recorder')
5
+ const event = require('../event')
6
+ const supportedHelpers = require('./standardActingHelpers')
7
+ const { scanForErrorMessages } = require('../html')
8
+ const { output } = require('..')
9
+ const { humanizeString, ucfirst } = require('../utils')
10
+ const { testToFileName } = require('../mocha/test')
11
+ const defaultConfig = {
12
+ errorClasses: ['error', 'warning', 'alert', 'danger'],
13
+ browserLogs: ['error'],
14
+ }
15
+
16
+ /**
17
+ * Collects information from web page after each failed test and adds it to the test as an artifact.
18
+ * It is suggested to enable this plugin if you run tests on CI and you need to debug failed tests.
19
+ * This plugin can be paired with `analyze` plugin to provide more context.
20
+ *
21
+ * It collects URL, HTML errors (by classes), and browser logs.
22
+ *
23
+ * Enable this plugin in config:
24
+ *
25
+ * ```js
26
+ * plugins: {
27
+ * pageInfo: {
28
+ * enabled: true,
29
+ * }
30
+ * ```
31
+ *
32
+ * Additional config options:
33
+ *
34
+ * * `errorClasses` - list of classes to search for errors (default: `['error', 'warning', 'alert', 'danger']`)
35
+ * * `browserLogs` - list of types of errors to search for in browser logs (default: `['error']`)
36
+ *
37
+ */
38
+ module.exports = function (config = {}) {
39
+ const helpers = Container.helpers()
40
+ let helper
41
+
42
+ config = Object.assign(defaultConfig, config)
43
+
44
+ for (const helperName of supportedHelpers) {
45
+ if (Object.keys(helpers).indexOf(helperName) > -1) {
46
+ helper = helpers[helperName]
47
+ }
48
+ }
49
+
50
+ if (!helper) return // no helpers for screenshot
51
+
52
+ event.dispatcher.on(event.test.failed, test => {
53
+ const pageState = {}
54
+
55
+ recorder.add('URL of failed test', async () => {
56
+ try {
57
+ const url = await helper.grabCurrentUrl()
58
+ pageState.url = url
59
+ } catch (err) {
60
+ // not really needed
61
+ }
62
+ })
63
+ recorder.add('HTML snapshot failed test', async () => {
64
+ try {
65
+ const html = await helper.grabHTMLFrom('body')
66
+
67
+ if (!html) return
68
+
69
+ const errors = scanForErrorMessages(html, config.errorClasses)
70
+ if (errors.length) {
71
+ output.debug('Detected errors in HTML code')
72
+ errors.forEach(error => output.debug(error))
73
+ pageState.htmlErrors = errors
74
+ }
75
+ } catch (err) {
76
+ // not really needed
77
+ }
78
+ })
79
+
80
+ recorder.add('Browser logs for failed test', async () => {
81
+ try {
82
+ const logs = await helper.grabBrowserLogs()
83
+
84
+ if (!logs) return
85
+
86
+ pageState.browserErrors = getBrowserErrors(logs, config.browserLogs)
87
+ } catch (err) {
88
+ // not really needed
89
+ }
90
+ })
91
+
92
+ recorder.add('Save page info', () => {
93
+ test.addNote('pageInfo', pageStateToMarkdown(pageState))
94
+
95
+ const pageStateFileName = path.join(global.output_dir, `${testToFileName(test)}.pageInfo.md`)
96
+ fs.writeFileSync(pageStateFileName, pageStateToMarkdown(pageState))
97
+ test.artifacts.pageInfo = pageStateFileName
98
+ return pageState
99
+ })
100
+ })
101
+ }
102
+
103
+ function pageStateToMarkdown(pageState) {
104
+ let markdown = ''
105
+
106
+ for (const [key, value] of Object.entries(pageState)) {
107
+ if (!value) continue
108
+ let result = ''
109
+
110
+ if (Array.isArray(value)) {
111
+ result = value.map(v => `- ${JSON.stringify(v, null, 2)}`).join('\n')
112
+ } else if (typeof value === 'string') {
113
+ result = `${value}`
114
+ } else {
115
+ result = JSON.stringify(value, null, 2)
116
+ }
117
+
118
+ if (!result.trim()) continue
119
+
120
+ markdown += `### ${ucfirst(humanizeString(key))}\n\n`
121
+ markdown += result
122
+ markdown += '\n\n'
123
+ }
124
+
125
+ return markdown
126
+ }
127
+
128
+ function getBrowserErrors(logs, type = ['error']) {
129
+ // Playwright & WebDriver console messages
130
+ let errors = logs
131
+ .map(log => {
132
+ if (typeof log === 'string') return log
133
+ if (!log.type) return null
134
+ return { type: log.type(), text: log.text() }
135
+ })
136
+ .filter(l => l && (typeof l === 'string' || type.includes(l.type)))
137
+ .map(l => (typeof l === 'string' ? l : l.text))
138
+
139
+ return errors
140
+ }
@@ -1,6 +1,8 @@
1
- module.exports = function () {
1
+ const { retryTo } = require('../effects')
2
+
3
+ module.exports = function (config) {
2
4
  console.log(`
3
- Deprecated Warning: 'retryTo' has been moved to the effects module.
5
+ Deprecation Warning: 'retryTo' has been moved to the effects module.
4
6
  You should update your tests to use it as follows:
5
7
 
6
8
  \`\`\`javascript
@@ -16,4 +18,10 @@ await retryTo((tryNum) => {
16
18
 
17
19
  For more details, refer to the documentation.
18
20
  `)
21
+
22
+ if (config.registerGlobal) {
23
+ global.retryTo = retryTo
24
+ }
25
+
26
+ return retryTo
19
27
  }
@@ -5,8 +5,9 @@ const Container = require('../container')
5
5
  const recorder = require('../recorder')
6
6
  const event = require('../event')
7
7
  const output = require('../output')
8
- const { fileExists, clearString } = require('../utils')
8
+ const { fileExists } = require('../utils')
9
9
  const Codeceptjs = require('../index')
10
+ const { testToFileName } = require('../mocha/test')
10
11
 
11
12
  const defaultConfig = {
12
13
  uniqueScreenshotNames: false,
@@ -63,7 +64,7 @@ module.exports = function (config) {
63
64
  }
64
65
 
65
66
  if (Codeceptjs.container.mocha()) {
66
- options.reportDir = Codeceptjs.container.mocha().options.reporterOptions && Codeceptjs.container.mocha().options.reporterOptions.reportDir
67
+ options.reportDir = Codeceptjs.container.mocha()?.options?.reporterOptions && Codeceptjs.container.mocha()?.options?.reporterOptions?.reportDir
67
68
  }
68
69
 
69
70
  if (options.disableScreenshots) {
@@ -71,21 +72,19 @@ module.exports = function (config) {
71
72
  return
72
73
  }
73
74
 
74
- event.dispatcher.on(event.test.failed, test => {
75
- if (test.ctx?._runnable.title.includes('hook: ')) {
76
- output.plugin('screenshotOnFail', 'BeforeSuite/AfterSuite do not have any access to the browser, hence it could not take screenshot.')
75
+ event.dispatcher.on(event.test.failed, (test, _err, hookName) => {
76
+ if (hookName === 'BeforeSuite' || hookName === 'AfterSuite') {
77
+ // no browser here
77
78
  return
78
79
  }
80
+
79
81
  recorder.add(
80
82
  'screenshot of failed test',
81
83
  async () => {
82
- let fileName = clearString(test.title)
83
84
  const dataType = 'image/png'
84
85
  // This prevents data driven to be included in the failed screenshot file name
85
- if (fileName.indexOf('{') !== -1) {
86
- fileName = fileName.substr(0, fileName.indexOf('{') - 3).trim()
87
- }
88
- if (test.ctx && test.ctx.test && test.ctx.test.type === 'hook') fileName = clearString(`${test.title}_${test.ctx.test.title}`)
86
+ let fileName = testToFileName(test)
87
+
89
88
  if (options.uniqueScreenshotNames && test) {
90
89
  const uuid = _getUUID(test)
91
90
  fileName = `${fileName.substring(0, 10)}_${uuid}.failed.png`
@@ -141,12 +140,8 @@ module.exports = function (config) {
141
140
  })
142
141
 
143
142
  function _getUUID(test) {
144
- if (test.uuid) {
145
- return test.uuid
146
- }
147
-
148
- if (test.ctx && test.ctx.test.uuid) {
149
- return test.ctx.test.uuid
143
+ if (test.uid) {
144
+ return test.uid
150
145
  }
151
146
 
152
147
  return Math.floor(new Date().getTime() / 1000)
@@ -121,12 +121,13 @@ module.exports = function (config) {
121
121
  deleteDir(dir)
122
122
  })
123
123
 
124
- event.dispatcher.on(event.test.failed, (test, err) => {
125
- if (test.ctx._runnable.title.includes('hook: ')) {
126
- output.plugin('stepByStepReport', 'BeforeSuite/AfterSuite do not have any access to the browser, hence it could not take screenshot.')
124
+ event.dispatcher.on(event.test.failed, (test, _err, hookName) => {
125
+ if (hookName === 'BeforeSuite' || hookName === 'AfterSuite') {
126
+ // no browser here
127
127
  return
128
128
  }
129
- persist(test, err)
129
+
130
+ persist(test)
130
131
  })
131
132
 
132
133
  event.dispatcher.on(event.all.result, () => {
@@ -1,5 +1,5 @@
1
1
  const event = require('../event')
2
- const { TIMEOUT_ORDER } = require('../step/timeout')
2
+ const { TIMEOUT_ORDER } = require('../timeout')
3
3
 
4
4
  const defaultConfig = {
5
5
  timeout: 150,