qase-tms / qase-javascript

Qase TMS JavaScript SDK
https://developers.qase.io
49 stars 43 forks source link

Getting Error Message : 'No files in payload' #369

Closed rohitiq closed 1 year ago

rohitiq commented 1 year ago
          let data = new FormData();
          data.append('file', 'data:image/png;name=image.png;base64,'+png);

          await fetch('https://api.qase.io/v1/attachment/SM', {
            method: 'POST',
            headers: {
                Accept: 'application/json',
                Token: ApiToken
            },
            body: data
        }).then(response => response.json())
                .then(response => console.log(response))
                .catch(err => console.error(err));
Screenshot 2023-02-21 at 10 02 30 AM
sklmx commented 1 year ago

Hi @rohitiq! Please, try this approach https://github.com/qase-tms/qase-javascript/blob/master/qase-core-reporter/src/reporter.ts#L610

rohitiq commented 1 year ago

in this approach, I'm getting the error 'FormData is not defined'

const options = { headers: { 'Content-Type': 'multipart/form-data; boundary=----WebKitFormBoundarysNZBGjpn4KIKf8OZ', }, }; const data = fs.createReadStream('/Users/rohit/Automation/pettycash/frontend/e2e/target/screenshots/failures/2023-2-2022-19-28.png');
const res = await qase.attachments.uploadAttachment('SM', [data], options); console.log(res.status)

Screenshot 2023-02-18 at 1 58 39 AM
sklmx commented 1 year ago

that means you didn’t import FormData properly

rohitiq commented 1 year ago

i used like this to import FormData in JS file

const FormData = require('form-data');

Screenshot 2023-02-21 at 1 11 10 PM

sklmx commented 1 year ago

Unfortunately, it's not easy to guess what's happening in your code. Could you provide a simple example that we could execute on our side? You don't need to provide any sensitive information.

rohitiq commented 1 year ago

i tried two ways to upload the attachment. in the first way I tried to upload attachments with uploadAttachment API. Below is the code

      // @ts-check
      // Protractor configuration file, see link for more information
       // https://github.com/angular/protractor/blob/master/lib/config.ts
       const { QaseApi } = require('qaseio');
       const FormData =  require('form-data');
      const crypto = require("crypto");

      const { SpecReporter } = require('jasmine-spec-reporter');
      const path = require("path");
      const qase = new QaseApi(process.env.TOKEN_QASE);

      /**
       * @type { import("protractor").Config }
       */
      exports.config = {
        allScriptsTimeout: 40000,
        suites: {
          sample: ['./src/specs/settings/*.sample.ts'],
        },
        specs: [

          './src/specs/settings/*.sample.ts',
        ],
        capabilities: {
          browserName: 'chrome',
        },
        directConnect: true,
        baseUrl: process.env.URL || 'https://www.google.com',
        framework: 'jasmine2',
        jasmineNodeOpts: {
          showColors: true,
          defaultTimeoutInterval: 120000,
          print: function() {}
        },
        useAllAngular2AppRoots: true,
        onPrepare() {
          afterEach(function () {
            // @ts-ignore
            browser.waitForAngularEnabled(true);
          });
          require('ts-node').register({
            project: require('path').join(__dirname, './tsconfig.json')
          });
          // @ts-ignore
          jasmine.getEnv().addReporter(new SpecReporter(
              { 
                spec: 
                {   
        displayStacktrace: true,
        displayErrorMessages: true,
        displayDuration: true, 
      } 
    }
  ));

  var fs = require('fs-extra');    
  jasmine.getEnv().addReporter({
    specDone: function (result) {
      //Extract QASE Test Case ID
      const str = result.description.split(':');
      const qaseTestCaseId = parseInt(str[0]);

      //Extract Duration
      const time = result.duration.toString().split(' ');
      const duration = parseInt(time[0]);

      if (result.status == 'failed') {
        var today = new Date();
        var todayDate = today.getFullYear() + '-' + (today.getMonth()+1) + '-' + today.getDate();
        var todayTime = today.getHours() + '-' + today.getMinutes() + '-' + today.getSeconds();
        const screenshotPath = path.resolve(__dirname + '/target/screenshots/failures/' + todayDate + '/');
        const fileName = todayTime + '.png';
        // @ts-ignore
        fs.mkdir(screenshotPath, { recursive: true }, err => {
          if (err) {
              throw err;
            }
        });
        // @ts-ignore
        browser.getCapabilities().then(function (caps) {
          // @ts-ignore
          browser.takeScreenshot().then(async function (png) {
            // console.log("Takinggggggg => " + png);
            console.log("Taking screenshot & saving it in => " + screenshotPath + fileName);
            var stream = fs.createWriteStream(screenshotPath + fileName);
            stream.write(Buffer.from(png, 'base64'));
            stream.end();

            let data = new FormData();

            data.append('file', 'data:image/png;name=image.png;base64,'+png);

            let customBoundary = '-----------------';
            crypto.randomBytes(24).forEach((value) => {
            customBoundary += Math.floor(value * 10).toString(8);
            });

            const options = {
              headers: {
                'Content-Type': 'multipart/form-data; boundary='+customBoundary
              }
          };

          const res = await qase.attachments.uploadAttachment(process.env.PROJECT_CODE, [data], options);
          console.log(res.data.result?.[0].hash);

          }, (err) => {
            console.log("Error while taking screenshot: " + err);
          });
        });

      }
    }
  });

  const jasmineReporters = require('jasmine-reporters');
  jasmine.getEnv().addReporter(new jasmineReporters.JUnitXmlReporter({
    consolidateAll: true,
    savePath: path.resolve(__dirname + '/target/test-results'),
    filePrefix: 'results'
  }));  
        },
        chromeDriver: '../node_modules/webdriver-manager/selenium/chromedriver_110.0.5481.77'
      };
Screenshot 2023-02-21 at 3 10 35 PM
rohitiq commented 1 year ago

In another way, I tried to upload an attachment with fetch method below is the code:

  // @ts-check
  // Protractor configuration file, see link for more information
  // https://github.com/angular/protractor/blob/master/lib/config.ts
  const { ResultCreateStatusEnum } = require('qaseio/dist/src/model');
  const { QaseApi } = require('qaseio');
  const FormData =  require('form-data');
  const {default : fetch} = require('node-fetch');

  const { SpecReporter } = require('jasmine-spec-reporter');
  const path = require("path");
  const qase = new QaseApi(process.env.TOKEN_QASE);

  /**
   * @type { import("protractor").Config }
   */
  exports.config = {
    allScriptsTimeout: 40000,
    suites: {
      sample: ['./src/specs/settings/*.sample.ts'],
    },
    specs: [
'./src/specs/sample/*.sample.ts',
    ],
    capabilities: {
      browserName: 'chrome',
    },
    directConnect: true,
    baseUrl: process.env.PETTYCASH_BASE_URL || 'https://pettycash.qubiqle.com',
    framework: 'jasmine2',
    jasmineNodeOpts: {
      showColors: true,
      defaultTimeoutInterval: 120000,
      print: function() {}
    },
    useAllAngular2AppRoots: true,
    onPrepare() {
      afterEach(function () {
  // @ts-ignore
  browser.waitForAngularEnabled(true);
});
require('ts-node').register({
  project: require('path').join(__dirname, './tsconfig.json')
});
// @ts-ignore
jasmine.getEnv().addReporter(new SpecReporter(
    { 
      spec: 
      {   
        displayStacktrace: true,
        displayErrorMessages: true,
        displayDuration: true, 
      } 
    }
  ));

  var fs = require('fs-extra');    
  jasmine.getEnv().addReporter({
    specDone: function (result) {
      //Extract QASE Test Case ID
      const str = result.description.split(':');
      const qaseTestCaseId = parseInt(str[0]);

      //Extract Duration
      const time = result.duration.toString().split(' ');
      const duration = parseInt(time[0]);

      if (result.status == 'failed') {
        var today = new Date();
        var todayDate = today.getFullYear() + '-' + (today.getMonth()+1) + '-' + today.getDate();
        var todayTime = today.getHours() + '-' + today.getMinutes() + '-' + today.getSeconds();
        const screenshotPath = path.resolve(__dirname + '/target/screenshots/failures/' + todayDate + '/');
        const fileName = todayTime + '.png';
        // @ts-ignore
        fs.mkdir(screenshotPath, { recursive: true }, err => {
          if (err) {
              throw err;
            }
        });
        // @ts-ignore
        browser.getCapabilities().then(function (caps) {
          // @ts-ignore
          browser.takeScreenshot().then(async function (png) {
            // console.log("Takinggggggg => " + png);
            console.log("Taking screenshot & saving it in => " + screenshotPath + fileName);
            var stream = fs.createWriteStream(screenshotPath + fileName);
            stream.write(Buffer.from(png, 'base64'));
            stream.end();

          let data = new FormData();

          data.append('file', 'data:image/png;name=image.png;base64,'+png);

          await fetch('https://api.qase.io/v1/attachment/PROJECT_CODE', {
            method: 'POST',
            headers: {
                Accept: 'application/json',
                Token: process.env.TOKEN_QASE
            },
            body: data
        }).then(response => response.json())
                .then(response => console.log(response))
                .catch(err => console.error(err));

          }, (err) => {
            console.log("Error while taking screenshot: " + err);
          });
        });

      }
    }
  });

  const jasmineReporters = require('jasmine-reporters');
  jasmine.getEnv().addReporter(new jasmineReporters.JUnitXmlReporter({
    consolidateAll: true,
    savePath: path.resolve(__dirname + '/target/test-results'),
    filePrefix: 'results'
  }));  
    },
   chromeDriver: '../node_modules/webdriver-manager/selenium/chromedriver_110.0.5481.77'
    };
Screenshot 2023-02-21 at 10 02 30 AM
rohitiq commented 1 year ago

any solution?

sklmx commented 1 year ago

The first example looks good. Do you have the form-data package installed?

rohitiq commented 1 year ago

yes, I already installed form-data package and import the same package in the file.

sklmx commented 1 year ago

@rohitiq I've created a repo with an example of use. Check it out.

rohitiq commented 1 year ago

it's working perfect. Thanks @sklmx