@testmonitor/playwright-reporter
Version:
The TestMonitor Playwright Reporter is a custom Playwright reporter that automatically sends your test results to TestMonitor.
4 lines (3 loc) • 9.87 kB
JavaScript
var _=Object.create;var h=Object.defineProperty;var O=Object.getOwnPropertyDescriptor;var U=Object.getOwnPropertyNames;var j=Object.getPrototypeOf,N=Object.prototype.hasOwnProperty;var M=(i,t)=>{for(var e in t)h(i,e,{get:t[e],enumerable:!0})},v=(i,t,e,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of U(t))!N.call(i,r)&&r!==e&&h(i,r,{get:()=>t[r],enumerable:!(s=O(t,r))||s.enumerable});return i};var g=(i,t,e)=>(e=i!=null?_(j(i)):{},v(t||!i||!i.__esModule?h(e,"default",{value:i,enumerable:!0}):e,i)),B=i=>v(h({},"__esModule",{value:!0}),i);var J={};M(J,{default:()=>S});module.exports=B(J);var b=g(require("os")),R=require("@testmonitor/ts-reporter-client");var P={name:"@testmonitor/playwright-reporter",version:"1.0.0",description:"The TestMonitor Playwright Reporter is a custom Playwright reporter that automatically sends your test results to TestMonitor.",keywords:["testmonitor","playwright","typescript"],homepage:"https://testmonitor.com",bugs:{url:"https://github.com/testmonitor/playwright-reporter/issues"},repository:{type:"git",url:"git+https://github.com/testmonitor/playwright-reporter.git"},author:"TestMonitor | we are Cerios B.V.",main:"./dist/index.js",types:"./dist/index.d.ts",files:["dist"],scripts:{typecheck:"tsc --noEmit","build:types":"tsc --emitDeclarationOnly","build:js":"tsup ./src/index.ts --format cjs,esm --minify",build:"npm run typecheck && npm run build:types && npm run build:js",lint:"eslint './src/**/*.{ts,tsx}' './tests/**/*.{ts,tsx}'","lint:fix":"eslint './src/**/*.{ts,tsx}' './tests/**/*.{ts,tsx}' --fix",prepare:"npm run build",test:"jest"},dependencies:{"@playwright/test":"^1.54.1","@testmonitor/ts-reporter-client":"^1.0.0",chalk:"^4.1.2",ora:"^5.4.1",table:"^6.9.0",uuid:"^11.1.0"},devDependencies:{"@eslint/js":"^9.24.0","@types/jest":"^29.5.14","@types/node":"^22.16.4","@typescript-eslint/eslint-plugin":"^8.30.1","@typescript-eslint/parser":"^8.30.1",eslint:"^9.24.0","eslint-config-prettier":"^10.1.5","eslint-formatter-junit":"^8.40.0","eslint-plugin-import":"^2.32.0","eslint-plugin-jest":"^28.14.0","eslint-plugin-jsdoc":"^50.6.11","eslint-plugin-promise":"^7.2.1",jest:"^29.7.0","jest-junit":"^16.0.0",prettier:"^3.6.2","ts-jest":"^29.4.0","ts-node":"^10.9.2",tsup:"^8.5.0",typescript:"^4.0 || ^5.0"},directories:{test:"tests"},engines:{node:">=18.0.0"}};function x(){return"1.0.0"}var A=require("fs"),d=class{static async generate(t){return t.body?await this.generateFileFromBody(t):await this.generateFileFromPath(t)}static async generateFileFromBody(t){return new File([t.body],t.name,{type:t.contentType})}static async generateFileFromPath(t){let e=t.path.split("/").pop()||t.path,s=(0,A.createReadStream)(t.path);return await this.streamToFile(s,t.contentType,e)}static async streamToFile(t,e,s){let r=[];return new Promise((n,c)=>{t.on("data",a=>r.push(a)).once("end",()=>{let a=new Blob(r,{type:e});n(new File([a],s,{type:e}))}).once("error",c)})}};var o=class{client;milestoneName;milestoneId;testEnvironmentId;attachmentBurstLimit=15;defaultAttachmentUploadDelay=50;burstLimitAttachmentUploadDelay=1500;constructor(t){this.milestoneId=t.milestoneId,this.milestoneName=t.milestoneName,this.testEnvironmentId=t.testEnvironmentId,this.client=new R.Client({domain:t.domain,token:t.token,createReportPath:"/api/v1/reporters/playwright/create",submitTestResultsPath:"/api/v1/reporters/playwright/submit",uploadAttachmentPath:"/api/v1/reporters/playwright/attachment",userAgent:this.generateUserAgent()})}async createReport(){return await this.client.createReport({milestoneId:this.milestoneId,milestoneName:this.milestoneName,testEnvironmentId:this.testEnvironmentId})}async submitTestResults(t,e){return await this.client.submitTestResults({reportId:t.id,data:e.toJson()})}async uploadAttachment(t,e){let s=await d.generate(e);await this.client.uploadAttachment({id:e.testCaseId,reportId:t.id,attachment:s})}getAttachmentUploadDelay(t){return t.length>this.attachmentBurstLimit?this.burstLimitAttachmentUploadDelay:this.defaultAttachmentUploadDelay}generateUserAgent(){let t=x(),e=`NodeJS/${process.version}`,s=`${b.default.platform()} ${b.default.release()}`;return`TestMonitorPlaywrightReporter/${t} (${e}; ${s}; +https://www.testmonitor.com/)`}};var y=g(require("chalk")),$=require("table"),f=class{prefix="TestMonitor";info(t){console.log(`${this.prefix}: ${t}`)}success(t){console.log(`${this.prefix}: ${y.default.green(t)}`)}error(t,e){console.error(`${this.prefix}: ${y.default.red(t)}`),process.env.DEBUG&&e instanceof Error&&console.error(y.default.gray(e.stack||e.message))}table(t,e){let s=(0,$.table)(t,{singleLine:!0,...e});console.log(s)}};function F(i){let t=i.getFullYear(),e=String(i.getMonth()+1).padStart(2,"0"),s=String(i.getDate()).padStart(2,"0"),r=String(i.getHours()).padStart(2,"0"),n=String(i.getMinutes()).padStart(2,"0"),c=String(i.getSeconds()).padStart(2,"0");return`${t}-${e}-${s} ${r}:${n}:${c}`}var T=g(require("chalk")),C=g(require("ora")),w=class{prefix="TestMonitor";spinner=null;start(t){this.spinner=(0,C.default)({text:`${this.prefix}: ${t}`,color:"green"}).start()}update(t){this.spinner&&(this.spinner.text=`${this.prefix}: ${t}`)}success(t){this.spinner?.succeed(`${this.prefix}: ${T.default.green(t)}`),this.spinner=null}fail(t){this.spinner?.fail(`${this.prefix}: ${T.default.red(t)}`),this.spinner=null}stop(){this.spinner?.stop(),this.spinner=null}};var D=require("uuid");var p=class{name;suites=[];testCases=[];constructor(t){this.name=t.name}addNestedSuite(t){this.suites.push(t)}addTestCase(t){this.testCases.push(t)}getSuites(){return this.suites}getTestCases(){return this.testCases}getName(){return this.name}};var u=class{id;name;instructions;status;description;attachments=[];duration;outcome;systemErr;systemOut;constructor(t){this.id=t.id,this.name=t.name,this.status=t.status,this.instructions=t.instructions,this.description=t.description,this.attachments=t.attachments,this.duration=t.duration,this.outcome=t.outcome,this.systemErr=t.systemErr,this.systemOut=t.systemOut}getId(){return this.id}getName(){return this.name}getInstructions(){return this.instructions}getStatus(){return this.status}getDescription(){return this.description||""}getAttachments(){return this.attachments}getDuration(){return this.duration}getOutcome(){return this.outcome}getSystemErr(){return this.systemErr||""}getSystemOut(){return this.systemOut||""}};var l=class{suites=[];startTime;duration;constructor(t,e,s){this.suites=t,this.startTime=e,this.duration=s}getSuites(){return this.suites}getAllTestCases(){return this.getSuites().flatMap(t=>this.getTestCasesFromSuite(t))}getTestCasesFromSuite(t){return[...t.getTestCases(),...t.getSuites().flatMap(e=>this.getTestCasesFromSuite(e))]}getAttachmentsByStatuses(t=[]){return this.getAllTestCases().filter(e=>t.length===0||t.includes(e.getStatus())).flatMap(e=>e.getAttachments())}getStartTime(){return this.startTime}getDuration(){return this.duration}toJson(){return{suites:this.getSuites().map(t=>this.suiteToJson(t)),start_time:this.getStartTime(),duration:this.getDuration()}}suiteToJson(t){return{name:t.getName(),suites:t.getSuites().map(e=>this.suiteToJson(e)),test_cases:t.getTestCases().map(e=>this.testCaseToJson(e))}}testCaseToJson(t){return{id:t.getId(),name:t.getName(),instructions:t.getInstructions(),description:t.getDescription(),status:t.getStatus(),duration:t.getDuration(),systemErr:t.getSystemErr(),systemOut:t.getSystemOut()}}};var m=class{static parse(t,e){let s=t.entries().filter(r=>r.type!=="test").map(r=>this.parseSuite(r));return new l(s,e.startTime,e.duration)}static parseSuite(t){let e=new p({name:t.title});return t.entries().filter(s=>s.type!=="test").forEach(s=>{e.addNestedSuite(this.parseSuite(s))}),t.entries().filter(s=>s.type==="test").forEach(s=>{e.addTestCase(this.parseTestCase(s))}),e}static parseTestCase(t){let e=t.results[0],s=this.generateTestCaseId();return new u({id:s,name:t.title,instructions:e.steps?e.steps.map(r=>r.title):[],status:e.status,description:e?.error?.stack,attachments:e.attachments.map(r=>({testCaseId:s,...r})),duration:e.duration,outcome:t.outcome(),systemErr:e?.stderr?.join(`
`),systemOut:e?.stdout?.join(`
`)})}static generateTestCaseId(){return(0,D.v7)()}};var S=class{reporter;suite;report;logger;spinner;attachmentStatuses=["failed","skipped","interrupted","timedOut"];constructor(t){this.reporter=new o(t),this.logger=new f,this.spinner=new w}async onBegin(t,e){this.spinner.start(`Waiting for ${e.allTests().length} tests to complete...`);try{this.suite=e,this.report=await this.reporter.createReport()}catch(s){let r=s.response?.data?.message||s.message;this.spinner.fail("An error occurred while creating the test run in TestMonitor."),this.logger.error(r,s)}}async onEnd(t){if(!(!this.report||!this.suite)){this.spinner.success("All Playwright tests finished."),this.spinner.start("Uploading test results...");try{let e=m.parse(this.suite,t),s=e.getAttachmentsByStatuses(this.attachmentStatuses),r=this.reporter.getAttachmentUploadDelay(s),n=await this.reporter.submitTestResults(this.report,e);this.spinner.success("Uploaded test results."),this.spinner.start(`Uploading ${s.length} attachment(s)...`);for(let[I,E]of s.entries())this.spinner.update(`Uploading ${I+1}/${s.length} attachment(s)...`),await new Promise(k=>setTimeout(k,r)),await this.reporter.uploadAttachment(n,E);this.spinner.success(`Uploaded ${s.length} attachment(s).`);let a=[["Playwright Test Status",`${t.status==="passed"?"\u2705":"\u274C"} ${t.status}`],["Playwright Test Start Time",F(new Date(t.startTime))],["Playwright Test Duration",`${(t.duration/1e3).toFixed(2)}s`],n.test_run.links.show?["Link to Test Run",n.test_run.links.show]:[]];this.logger.table(a)}catch(e){let s=e.response?.data?.message||e.message;this.spinner.fail("An error occurred while uploading the test results to TestMonitor."),this.logger.error(s,e)}}}};
;