You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
I'm Gabriel Souza, Developer and QA Analyst at GRV Software, Vinhedo - São Paulo - Brazil.
I recently added a feature that was not included in the Cypress documentation. The idea is to automatically send the reports generated after the tests in email using Github actions.
In the root of the test there will be a file called sendReport.js which contains all the sending information with the reports generated after the tests.
These files will have a limit of 25MB, which is the maximum allowed per attachment.
require('dotenv').config()constnodemailer=require('nodemailer')constpath=require('path')constfs=require('fs')const{ create }=require('html-pdf-chrome')constpuppeteer=require('puppeteer')constMAX_ATTACHMENT_SIZE=24*1024*1024asyncfunctionensureDirectoryExists(directoryPath){try{awaitfs.promises.mkdir(directoryPath,{recursive: true})console.warn(`Diretório criado ou já existe: ${directoryPath}`)}catch(error){console.error('Erro ao criar diretório:',error)}}asyncfunctioncaptureScreenshot(url,outputPath){try{constbrowser=awaitpuppeteer.launch({headless: true,executablePath: '/usr/bin/chromium-browser',})constpage=awaitbrowser.newPage()awaitpage.goto(`file://${url}`,{waitUntil: 'networkidle2'})awaitpage.screenshot({path: outputPath,fullPage: true})awaitbrowser.close()console.debug('Screenshot capturada com sucesso:',outputPath)}catch(error){console.error('Erro ao capturar screenshot:',error)}}functionfindVideoFileDynamically(videoDir){try{if(!fs.existsSync(videoDir)){console.warn('Diretório de vídeos não existe:',videoDir)returnnull}constdirectories=fs.readdirSync(videoDir,{withFileTypes: true})for(constdirofdirectories){if(dir.isDirectory()){constsubDirPath=path.join(videoDir,dir.name)constfiles=fs.readdirSync(subDirPath)constvideoFile=files.find(file=>file.endsWith('.mp4'))if(videoFile){console.debug(`Vídeo encontrado: ${videoFile} em ${subDirPath}`)returnpath.join(subDirPath,videoFile)}}}console.warn('Nenhum arquivo de vídeo encontrado nos subdiretórios:',videoDir)returnnull}catch(error){console.error('Erro ao procurar o arquivo de vídeo nos subdiretórios:',error)returnnull}}asyncfunctionsendEmailWithAttachment(pdfPath,screenshotPath,videoPath){constattachments=[{filename: 'relatorio-cypress.pdf',path: pdfPath,},{filename: 'screenshot.png',path: screenshotPath,},]if(videoPath&&fs.existsSync(videoPath)){constvideoStats=awaitfs.promises.stat(videoPath)consttotalSize=awaitcalculateTotalAttachmentSize(attachments)if(totalSize+videoStats.size<=MAX_ATTACHMENT_SIZE){attachments.push({filename: 'video.mp4',path: videoPath,})}else{console.warn('O tamanho total dos anexos excede 20MB, vídeo não será anexado.')}}else{console.warn(`Arquivo de vídeo não encontrado ou inválido: ${videoPath}`)}constmailOptions={from: process.env.EMAIL,to: process.env.RECIPIENT,subject: 'Relatório de Testes Cypress',html: '<h3>Segue o relatório de testes do Cypress</h3>',
attachments,}try{constinfo=awaittransporter.sendMail(mailOptions)console.debug('E-mail enviado com sucesso:',info.response)}catch(error){console.error('Erro ao enviar o e-mail:',error)}}asyncfunctionconvertHtmlToPdf(htmlFilePath,outputPdfPath){try{if(!fs.existsSync(htmlFilePath)){console.error('Erro: Arquivo HTML não encontrado:',htmlFilePath)return}consthtmlContent=awaitfs.promises.readFile(htmlFilePath,'utf-8')constoptions={launchOptions: {headless: true,executablePath: '/usr/bin/google-chrome',},printOptions: {format: 'A4',landscape: true,printBackground: true,preferCSSPageSize: true,},}constpdf=awaitcreate(htmlContent,options)awaitnewPromise(resolve=>setTimeout(resolve,5000))awaitpdf.toFile(outputPdfPath)console.debug('Relatório convertido para PDF com sucesso:',outputPdfPath)}catch(error){console.error('Erro ao gerar o PDF:',error)}}asyncfunctioncalculateTotalAttachmentSize(attachments){lettotalSize=0for(constattachmentofattachments){try{conststats=awaitfs.promises.stat(attachment.path)totalSize+=stats.size}catch(error){console.error('Erro ao calcular o tamanho do anexo:',error)}}returntotalSize}consttransporter=nodemailer.createTransport({host: 'smtp.gmail.com',port: 465,secure: true,auth: {user: process.env.EMAIL,pass: process.env.PASSWORD,},})constreportsDir=path.resolve(__dirname,'cypress/reports')constreportPath=path.join(reportsDir,'html','index.html')constpdfDir=path.join(reportsDir,'pdf')constpdfPath=path.join(pdfDir,'relatorio-cypress.pdf')constvideoDir=path.join('cypress/videos')constscreenshotPath=path.join(pdfDir,'relatorio-cypress.png')ensureDirectoryExists(pdfDir).then(async()=>{try{awaitconvertHtmlToPdf(reportPath,pdfPath)awaitcaptureScreenshot(reportPath,screenshotPath)constvideoPath=findVideoFileDynamically(videoDir)if(!fs.existsSync(pdfPath)){console.error('Erro: O arquivo PDF não foi gerado corretamente.')return}awaitsendEmailWithAttachment(pdfPath,screenshotPath,videoPath)}catch(error){console.error('Erro durante o processamento:',error)}})
There will be a .env file that stores the sender and recipient email addresses with the security key.
in the path ".github/workflows/ci.yml", in addition to running the tests, it will also be responsible for sending the email if there are errors in the tests.
The files generated by the tests will be made available in the Github actions.
Why is this needed?
This is necessary to reduce the manual work of converting html to pdf, capturing screenshots, and recording video with third-party software, and also so that the recipients (whether a supervisor or a manager in charge of the department) are aware of possible errors that the tests have captured.
Hi @jennifer-shehane, what's up?
That's what it would be for too ... but it's also an idea of what can be added to the documentation as an option to send a personalized email with all the information from the test run in the github actions.
What would you like?
Hello, good morning... what's up?
I'm Gabriel Souza, Developer and QA Analyst at GRV Software, Vinhedo - São Paulo - Brazil.
I recently added a feature that was not included in the Cypress documentation. The idea is to automatically send the reports generated after the tests in email using Github actions.
Why is this needed?
This is necessary to reduce the manual work of converting html to pdf, capturing screenshots, and recording video with third-party software, and also so that the recipients (whether a supervisor or a manager in charge of the department) are aware of possible errors that the tests have captured.
Other
If you have any questions about this idea, check out my repost https://github.com/GbrlSouza/cypress_with_email
The text was updated successfully, but these errors were encountered: