|
1 | | -import React from 'react' |
2 | | -import { render, cleanup } from 'react-testing-library' |
3 | | -import invariant from 'invariant' |
4 | | -import uuid from 'uuid-v4' |
5 | | - |
6 | | -const renderHook = (hook, context) => (props) => { |
7 | | - |
8 | | - const containerId = uuid() |
9 | | - |
10 | | - const HookHarness = (props) => { |
11 | | - context.result = hook(props) |
12 | | - return <div data-testid={containerId} /> |
13 | | - } |
14 | | - |
15 | | - const { queryByTestId, rerender } = render(context.resolveComponent({ children: <HookHarness {...props} /> })) |
16 | | - |
17 | | - const container = queryByTestId(containerId) |
18 | | - |
19 | | - invariant(container !== null, 'You must render children when wrapping the hook') |
20 | | - |
21 | | - context.rerender = (newProps) => rerender(context.resolveComponent({ children: <HookHarness {...newProps} /> })) |
22 | | - context.flushEffects = () => rerender(context.resolveComponent({ children: <HookHarness {...props} /> })) |
23 | | - |
24 | | - return context.result |
25 | | -} |
26 | | - |
27 | | -const updateHook = (context) => (props) => { |
28 | | - invariant(context.rerender, 'You must render the hook before it can be updated') |
29 | | - |
30 | | - context.rerender(props) |
31 | | - |
32 | | - return context.result |
33 | | -} |
34 | | - |
35 | | -const flushHookEffects = (context) => () => { |
36 | | - invariant(context.rerender, 'You must render the hook before effects can be flushed') |
37 | | - |
38 | | - context.flushEffects() |
39 | | - |
40 | | - return context.result |
41 | | -} |
42 | | - |
43 | | -const wrapHook = (hook, context) => (wrap) => { |
44 | | - invariant(typeof wrap === 'function', 'wrap must be provided a function') |
45 | | - const { resolveComponent } = context |
46 | | - return useHookAdvanced(hook, { ...context, resolveComponent: (props) => wrap({ children: resolveComponent(props) }) }) |
47 | | -} |
48 | | - |
49 | | -const useHookAdvanced = (hook, context) => { |
50 | | - return { |
51 | | - render: renderHook(hook, context), |
52 | | - update: updateHook(context), |
53 | | - flushEffects: flushHookEffects(context), |
54 | | - wrap: wrapHook(hook, context) |
55 | | - } |
56 | | -} |
57 | | - |
58 | | -export const useHook = (hook) => useHookAdvanced(hook, { resolveComponent: ({ children }) => children }) |
59 | | - |
60 | | -export { cleanup } |
| 1 | +export * from './useHook' |
0 commit comments