Skip to content

Commit e40969a

Browse files
fix: improve React mountHook type (#17241)
* feat(react) : improve mountHook types * chore: Remove wrapping which causes test failing Co-authored-by: Lachlan Miller <lachlan.miller.1990@outlook.com>
1 parent 8fca932 commit e40969a

File tree

1 file changed

+25
-19
lines changed

1 file changed

+25
-19
lines changed

npm/react/src/mountHook.ts

+25-19
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,22 @@
11
import * as React from 'react'
2+
23
import { mount } from './mount'
34

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+
417
// mounting hooks inside a test component mostly copied from
518
// https://github.com/testing-library/react-hooks-testing-library/blob/master/src/pure.js
6-
function resultContainer<T> () {
19+
function resultContainer<T> (): ResultContainer<T> {
720
let value: T | undefined | null = null
821
let error: Error | null = null
922
const resolvers: any[] = []
@@ -29,7 +42,7 @@ function resultContainer<T> () {
2942

3043
return {
3144
result,
32-
addResolver: (resolver: any) => {
45+
addResolver: (resolver: (() => void)) => {
3346
resolvers.push(resolver)
3447
},
3548
setValue: (val: T) => updateResult(val),
@@ -46,36 +59,29 @@ type TestHookProps = {
4659
function TestHook ({ callback, onError, children }: TestHookProps) {
4760
try {
4861
children(callback())
49-
} catch (err) {
50-
if (err.then) {
62+
} catch (err: any) {
63+
if ('then' in err) {
5164
throw err
5265
} else {
5366
onError(err)
5467
}
5568
}
5669

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>
6170
return null
6271
}
6372

6473
/**
6574
* Mounts a React hook function in a test component for testing.
6675
*
67-
* @see https://github.com/bahmutov/@cypress/react#advanced-examples
6876
*/
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>()
7179

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,
8084
})
85+
86+
return mount(componentTest).then(() => result)
8187
}

0 commit comments

Comments
 (0)