|
| 1 | +import { Plugin } from '@bellatrix/core/infrastructure'; |
| 2 | +import { TestMetadata } from '@bellatrix/core/test/props'; |
| 3 | +import { ServiceLocator } from '@bellatrix/core/utilities'; |
| 4 | +import { App } from '@bellatrix/web/infrastructure'; |
| 5 | +import * as fs from 'fs'; |
| 6 | +import * as path from 'path'; |
| 7 | + |
| 8 | +export class ScreenshotOnFailPlugin extends Plugin { |
| 9 | + override async preAfterTest(metadata: TestMetadata): Promise<void> { |
| 10 | + if(metadata.error !== undefined) { |
| 11 | + const app = ServiceLocator.resolve(App); |
| 12 | + const screenshotImage = await app.browser.getScreenshot(); |
| 13 | + // Save the screenshot as an image file |
| 14 | + try { |
| 15 | + const savePath = this.saveImageFromBase64(screenshotImage.base64, '../reports/screenshots/' + metadata.testName); // TODO: take from config |
| 16 | + console.info('\n Screenshot for failed test ' + metadata.testName + ': ' + savePath + '\n'); |
| 17 | + } catch (error) { |
| 18 | + console.error('Error saving screenshot:', (error as Error).message); |
| 19 | + } |
| 20 | + } |
| 21 | + } |
| 22 | + |
| 23 | + /** |
| 24 | + * Save a Base64 string as an image file |
| 25 | + * @param base64String - The Base64 string of the image |
| 26 | + * @param outputPath - The path to save the image file |
| 27 | + */ |
| 28 | + private saveImageFromBase64(base64String: string, outputPath: string): string { |
| 29 | + // Check if the Base64 string contains the data prefix (e.g., "data:image/png;base64,") |
| 30 | + let matches = base64String.match(/^data:image\/([a-zA-Z]+);base64,(.+)$/); |
| 31 | + if (!matches || matches.length !== 3) { |
| 32 | + base64String = 'data:image/png;base64,' + base64String; |
| 33 | + matches = base64String.match(/^data:image\/([a-zA-Z]+);base64,(.+)$/); |
| 34 | + } |
| 35 | + // Extract the file extension and the Base64-encoded data |
| 36 | + const fileExtension = matches[1]; // e.g., 'png', 'jpeg', etc. |
| 37 | + const base64Data = matches[2]; |
| 38 | + // Decode the Base64 string into binary data |
| 39 | + const binaryData = Buffer.from(base64Data, 'base64'); |
| 40 | + const arrayBufferView: Uint8Array = new Uint8Array(binaryData.buffer, binaryData.byteOffset, binaryData.length); |
| 41 | + // Ensure the output directory exists |
| 42 | + const outputDir = path.dirname(outputPath); |
| 43 | + if (!fs.existsSync(outputDir)) { |
| 44 | + fs.mkdirSync(outputDir, { recursive: true }); |
| 45 | + } |
| 46 | + // Determine the output file path (with the correct file extension) |
| 47 | + const outputFilePath = path.extname(outputPath) |
| 48 | + ? outputPath |
| 49 | + : `${outputPath}.${fileExtension}`; |
| 50 | + // Write the binary data to a file |
| 51 | + fs.writeFileSync(outputFilePath, arrayBufferView); |
| 52 | + return outputFilePath; |
| 53 | + } |
| 54 | +} |
0 commit comments