cypress mochawesome reporter screenshot as base64

41 Views Asked by At

I am currently trying to create and email a html report with screenshots via mochawesome. In order for it to be emailed, I have been trying to turn the png images into base64 to inline it into the html file. However, I am not able to do so successfully... I have tired different methods to encode the png to base64, such as FileReader, cy.readFile, fs.readFileSync, image-to-base64 npm package, etc with not much success. Wondering if there's a specific way to be able to do this for Cypress and if anyone can help.

Cypress.on('test:after:run', (test, runnable) => {
  if(test.state === 'failed' && test.currentRetry === test.retries){
    const title = test.title.replace('.', "").replace('#', '%23');
    const parentTitle = runnable.parent.title.replace(".", "");
    const filePath = (test.retries == 0) ? 
      `${Cypress.config('screenshotsFolder')}/${Cypress.spec.name}/${parentTitle} -- ${title} (failed).png`
      : `${Cypress.config('screenshotsFolder')}/${Cypress.spec.name}/${parentTitle} -- ${title} (failed) (attempt 2).png`;
    const fs = require("fs")
    const pngAsBase64 = fs.readFileSync(filePath, "base64")
    addContext({ test }, "data:image/png;base64," + pngAsBase64);
  };
})
1

There are 1 best solutions below

1
Lort.Nielsen On

The syntax of encoding in fs.readFileSync appears to be incorrect.

From node-js-fs-readfilesync-method/

Syntax:

fs.readFileSync( path, options )

  • options: It is an optional parameter that contains the encoding and flag, the encoding contains data specification. Its default value is null which returns the raw buffer and the flag contains an indication of operations in the file. Its default value is ‘r’.

const data = fs.readFileSync('./input.txt', { encoding: 'utf8', flag: 'r' });

Change this line:

const pngAsBase64 = fs.readFileSync(filePath, {encoding: 'base64'})