Closed rohitiq closed 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
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)
that means you didn’t import FormData properly
i used like this to import FormData in JS file
const FormData = require('form-data');
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.
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'
};
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'
};
any solution?
The first example looks good. Do you have the form-data package installed?
yes, I already installed form-data package and import the same package in the file.
it's working perfect. Thanks @sklmx