source: https://github.com/kentcdodds/react-testing-library/pull/307/files
Last active
February 25, 2019 07:02
-
-
Save smmoosavi/b8350c03385f0827ae1cff1d4f00e512 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from 'react'; | |
import { render, RenderOptions } from 'react-testing-library'; | |
function TestHook<T>({ | |
callback, | |
children, | |
}: { | |
callback: () => T; | |
children: (result: T) => void; | |
}) { | |
children(callback()); | |
return null; | |
} | |
export type HookResult<TResult> = { | |
result: React.MutableRefObject<TResult>; | |
rerender: () => void; | |
unmount: () => boolean; | |
}; | |
export type HookOptions = RenderOptions; | |
/** | |
* Renders a test component that calls back to the test. | |
*/ | |
export function testHook<T>( | |
callback: () => T, | |
options?: Partial<HookOptions>, | |
): HookResult<T>; | |
export function testHook<T>(callback: () => T, options = {}): HookResult<T> { | |
const result: { current: null | T } = { | |
current: null, | |
}; | |
const toRender = () => ( | |
<TestHook callback={callback}> | |
{(res: T) => { | |
result.current = res; | |
}} | |
</TestHook> | |
); | |
const { unmount, rerender: rerenderComponent } = render(toRender(), options); | |
return { | |
// @ts-ignore | |
result, | |
unmount, | |
rerender: () => { | |
rerenderComponent(toRender()); | |
}, | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment