11"use strict" ;
22
3+ const fs = require ( 'fs' ) ;
4+ const path = require ( 'path' ) ;
5+ const crypto = require ( 'crypto' ) ;
36const { test } = require ( "@playwright/test" ) ;
47
8+ const istanbulCLIOutput = path . join ( process . cwd ( ) , '.nyc_output' ) ;
9+
10+ function generateUUID ( ) {
11+ return crypto . randomBytes ( 16 ) . toString ( 'hex' ) ;
12+ }
13+
514const customTest = test . extend ( {
615 done : [
716 // eslint-disable-next-line no-empty-pattern
@@ -17,6 +26,25 @@ const customTest = test.extend({
1726 } ,
1827 { option : true } ,
1928 ] ,
29+ context : async ( { context } , use ) => {
30+ await context . addInitScript ( ( ) =>
31+ // eslint-disable-next-line no-undef
32+ window . addEventListener ( 'beforeunload' , ( ) =>
33+ // eslint-disable-next-line no-undef
34+ window . collectIstanbulCoverage ( JSON . stringify ( window . __coverage__ ) )
35+ ) ,
36+ )
37+ await fs . promises . mkdir ( istanbulCLIOutput , { recursive : true } ) ;
38+ await context . exposeFunction ( 'collectIstanbulCoverage' , ( coverageJSON ) => {
39+ if ( coverageJSON )
40+ { fs . writeFileSync ( path . join ( istanbulCLIOutput , `playwright_coverage_${ generateUUID ( ) } .json` ) , coverageJSON ) ; }
41+ } ) ;
42+ await use ( context ) ;
43+ for ( const page of context . pages ( ) ) {
44+ // eslint-disable-next-line no-await-in-loop,no-undef
45+ await page . evaluate ( ( ) => window . collectIstanbulCoverage ( JSON . stringify ( window . __coverage__ ) ) )
46+ }
47+ }
2048} ) ;
2149
2250module . exports = { test : customTest } ;
0 commit comments