1
1
import * as React from 'react'
2
+
2
3
import { mount } from './mount'
3
4
5
+ type MountHookResult < T > = {
6
+ readonly current : T | null | undefined
7
+ readonly error : Error | null
8
+ }
9
+
10
+ type ResultContainer < T > = {
11
+ result : MountHookResult < T >
12
+ addResolver : ( resolver : ( ) => void ) => void
13
+ setValue : ( val : T ) => void
14
+ setError : ( err : Error ) => void
15
+ }
16
+
4
17
// mounting hooks inside a test component mostly copied from
5
18
// https://github.com/testing-library/react-hooks-testing-library/blob/master/src/pure.js
6
- function resultContainer < T > ( ) {
19
+ function resultContainer < T > ( ) : ResultContainer < T > {
7
20
let value : T | undefined | null = null
8
21
let error : Error | null = null
9
22
const resolvers : any [ ] = [ ]
@@ -29,7 +42,7 @@ function resultContainer<T> () {
29
42
30
43
return {
31
44
result,
32
- addResolver : ( resolver : any ) => {
45
+ addResolver : ( resolver : ( ( ) => void ) ) => {
33
46
resolvers . push ( resolver )
34
47
} ,
35
48
setValue : ( val : T ) => updateResult ( val ) ,
@@ -46,36 +59,29 @@ type TestHookProps = {
46
59
function TestHook ( { callback, onError, children } : TestHookProps ) {
47
60
try {
48
61
children ( callback ( ) )
49
- } catch ( err ) {
50
- if ( err . then ) {
62
+ } catch ( err : any ) {
63
+ if ( ' then' in err ) {
51
64
throw err
52
65
} else {
53
66
onError ( err )
54
67
}
55
68
}
56
69
57
- // TODO decide what the test hook component should show
58
- // maybe nothing, or maybe useful information about the hook?
59
- // maybe its current properties?
60
- // return <div>TestHook</div>
61
70
return null
62
71
}
63
72
64
73
/**
65
74
* Mounts a React hook function in a test component for testing.
66
75
*
67
- * @see https://github.com/bahmutov/@cypress/react#advanced-examples
68
76
*/
69
- export const mountHook = ( hookFn : ( ...args : any [ ] ) => any ) => {
70
- const { result, setValue, setError } = resultContainer ( )
77
+ export const mountHook = < T > ( hookFn : ( ...args : any [ ] ) => T ) => {
78
+ const { result, setValue, setError } = resultContainer < T > ( )
71
79
72
- return mount (
73
- React . createElement ( TestHook , {
74
- callback : hookFn ,
75
- onError : setError ,
76
- children : setValue ,
77
- } ) ,
78
- ) . then ( ( ) => {
79
- cy . wrap ( result )
80
+ const componentTest : React . ReactElement = React . createElement ( TestHook , {
81
+ callback : hookFn ,
82
+ onError : setError ,
83
+ children : setValue ,
80
84
} )
85
+
86
+ return mount ( componentTest ) . then ( ( ) => result )
81
87
}
0 commit comments