1
1
"use strict" ;
2
2
3
+ const fs = require ( 'fs' ) ;
4
+ const path = require ( 'path' ) ;
5
+ const crypto = require ( 'crypto' ) ;
3
6
const { test } = require ( "@playwright/test" ) ;
4
7
8
+ const istanbulCLIOutput = path . join ( process . cwd ( ) , '.nyc_output' ) ;
9
+
10
+ function generateUUID ( ) {
11
+ return crypto . randomBytes ( 16 ) . toString ( 'hex' ) ;
12
+ }
13
+
5
14
const customTest = test . extend ( {
6
15
done : [
7
16
// eslint-disable-next-line no-empty-pattern
@@ -17,6 +26,25 @@ const customTest = test.extend({
17
26
} ,
18
27
{ option : true } ,
19
28
] ,
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
+ }
20
48
} ) ;
21
49
22
50
module . exports = { test : customTest } ;
0 commit comments