UNPKG

@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.2 kB
import b from"os";import{Client as F}from"@testmonitor/ts-reporter-client";var w={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 S(){return"1.0.0"}import{createReadStream as $}from"fs";var h=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=$(t.path);return await this.streamToFile(s,t.contentType,e)}static async streamToFile(t,e,s){let i=[];return new Promise((n,c)=>{t.on("data",a=>i.push(a)).once("end",()=>{let a=new Blob(i,{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 F({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 h.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=S(),e=`NodeJS/${process.version}`,s=`${b.platform()} ${b.release()}`;return`TestMonitorPlaywrightReporter/${t} (${e}; ${s}; +https://www.testmonitor.com/)`}};import y from"chalk";import{table as C}from"table";var g=class{prefix="TestMonitor";info(t){console.log(`${this.prefix}: ${t}`)}success(t){console.log(`${this.prefix}: ${y.green(t)}`)}error(t,e){console.error(`${this.prefix}: ${y.red(t)}`),process.env.DEBUG&&e instanceof Error&&console.error(y.gray(e.stack||e.message))}table(t,e){let s=C(t,{singleLine:!0,...e});console.log(s)}};function T(r){let t=r.getFullYear(),e=String(r.getMonth()+1).padStart(2,"0"),s=String(r.getDate()).padStart(2,"0"),i=String(r.getHours()).padStart(2,"0"),n=String(r.getMinutes()).padStart(2,"0"),c=String(r.getSeconds()).padStart(2,"0");return`${t}-${e}-${s} ${i}:${n}:${c}`}import v from"chalk";import D from"ora";var d=class{prefix="TestMonitor";spinner=null;start(t){this.spinner=D({text:`${this.prefix}: ${t}`,color:"green"}).start()}update(t){this.spinner&&(this.spinner.text=`${this.prefix}: ${t}`)}success(t){this.spinner?.succeed(`${this.prefix}: ${v.green(t)}`),this.spinner=null}fail(t){this.spinner?.fail(`${this.prefix}: ${v.red(t)}`),this.spinner=null}stop(){this.spinner?.stop(),this.spinner=null}};import{v7 as I}from"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(i=>i.type!=="test").map(i=>this.parseSuite(i));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(i=>i.title):[],status:e.status,description:e?.error?.stack,attachments:e.attachments.map(i=>({testCaseId:s,...i})),duration:e.duration,outcome:t.outcome(),systemErr:e?.stderr?.join(` `),systemOut:e?.stdout?.join(` `)})}static generateTestCaseId(){return I()}};var f=class{reporter;suite;report;logger;spinner;attachmentStatuses=["failed","skipped","interrupted","timedOut"];constructor(t){this.reporter=new o(t),this.logger=new g,this.spinner=new d}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 i=s.response?.data?.message||s.message;this.spinner.fail("An error occurred while creating the test run in TestMonitor."),this.logger.error(i,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),i=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[P,x]of s.entries())this.spinner.update(`Uploading ${P+1}/${s.length} attachment(s)...`),await new Promise(A=>setTimeout(A,i)),await this.reporter.uploadAttachment(n,x);this.spinner.success(`Uploaded ${s.length} attachment(s).`);let a=[["Playwright Test Status",`${t.status==="passed"?"\u2705":"\u274C"} ${t.status}`],["Playwright Test Start Time",T(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)}}}};export{f as default};