Skip to content

Instantly share code, notes, and snippets.

@smmoosavi
Last active February 25, 2019 07:02
Show Gist options
  • Save smmoosavi/b8350c03385f0827ae1cff1d4f00e512 to your computer and use it in GitHub Desktop.
Save smmoosavi/b8350c03385f0827ae1cff1d4f00e512 to your computer and use it in GitHub Desktop.
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