1
1
import { readFileSync } from 'fs'
2
2
import * as path from 'path'
3
- import { ElementHandle , EvaluateFn , Page } from 'puppeteer'
3
+ import { ElementHandle , EvaluateFn , JSHandle , Page } from 'puppeteer'
4
4
import { ITestUtils } from './typedefs'
5
5
6
6
const domLibraryAsString = readFileSync (
@@ -25,13 +25,36 @@ type DOMReturnType = ElementHandle | ElementHandle[] | null
25
25
26
26
type ContextFn = ( ...args : any [ ] ) => ElementHandle
27
27
28
+ async function createElementHandleArray ( handle : JSHandle ) : Promise < ElementHandle [ ] > {
29
+ const lengthHandle = await handle . getProperty ( 'length' )
30
+ const length = await lengthHandle . jsonValue ( )
31
+
32
+ const elements : ElementHandle [ ] = [ ]
33
+ for ( let i = 0 ; i < length ; i ++ ) {
34
+ const jsElement = await handle . getProperty ( i . toString ( ) )
35
+ const element = await createElementHandle ( jsElement )
36
+ if ( element ) elements . push ( element )
37
+ }
38
+
39
+ return elements
40
+ }
41
+
42
+ async function createElementHandle ( handle : JSHandle ) : Promise < ElementHandle | null > {
43
+ const element = handle . asElement ( )
44
+ if ( element ) return element
45
+ await handle . dispose ( )
46
+ return null // tslint:disable-line
47
+ }
48
+
49
+ async function covertToElementHandle ( handle : JSHandle , asArray : boolean ) : Promise < DOMReturnType > {
50
+ return asArray ? createElementHandleArray ( handle ) : createElementHandle ( handle )
51
+ }
52
+
28
53
function createDelegateFor (
29
54
fnName : keyof ITestUtils ,
30
55
contextFn ?: ContextFn ,
31
56
) : ( ...args : any [ ] ) => Promise < DOMReturnType > {
32
57
return async function ( ...args : any [ ] ) : Promise < DOMReturnType > {
33
- if ( fnName . includes ( 'All' ) ) throw new Error ( '*All methods not yet supported' )
34
-
35
58
// @ts -ignore
36
59
const containerHandle : ElementHandle = contextFn ? contextFn ( ...args ) : this
37
60
// @ts -ignore
@@ -45,16 +68,13 @@ function createDelegateFor(
45
68
const handle = await containerHandle
46
69
. executionContext ( )
47
70
. evaluateHandle ( evaluateFn , containerHandle , fnName , ...argsToForward )
48
- const element = handle . asElement ( )
49
- if ( element ) return element
50
- await handle . dispose ( )
51
- return null // tslint:disable-line
71
+ return covertToElementHandle ( handle , fnName . includes ( 'All' ) )
52
72
}
53
73
}
54
74
55
- export async function getDocument ( context ?: Page ) : Promise < ElementHandle > {
75
+ export async function getDocument ( _page ?: Page ) : Promise < ElementHandle > {
56
76
// @ts -ignore
57
- const page : Page = context || this
77
+ const page : Page = _page || this
58
78
const documentHandle = await page . mainFrame ( ) . evaluateHandle ( 'document' )
59
79
const document = documentHandle . asElement ( )
60
80
if ( ! document ) throw new Error ( 'Could not find document' )
0 commit comments