-
Notifications
You must be signed in to change notification settings - Fork 115
/
Copy pathhook.js
70 lines (66 loc) · 2.32 KB
/
hook.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import React, { Component } from 'react';
import hoistNonReactStatic from 'hoist-non-react-statics';
import PropTypes from 'prop-types';
import TestHookStore from './TestHookStore';
import { TesterContext } from './Tester';
import generateTestHook from './generateTestHook';
// Public: Higher-order React component to factilitate adding hooks to the
// global test hook store. Once you've hooked your main component (see example
// below), you can set an inner component's ref with `this.props.generateTestHook`
// to add it to the testHookStore for later use in a spec.
//
// React will call `generateTestHook` twice during the render lifecycle; once to
// 'unset' the ref, and once to set it.
//
// WrappedComponent - Component to be wrapped, will be passed an initial
// property called 'generateTestHook' which is a function
// generator that will add a component to the testHookStore.
//
// Example
//
// import { hook } from 'cavy';
//
// class MyComponent extends React.Component {
//
// render() {
// const { generateTestHook } = this.props;
// return (
// <TextInput
// ref={generateTestHook('MyComponent.textinput', (c) => this.textInput = c)}
// ...
// />
// <Button
// ref={generateTestHook('MyComponent.button')}
// title='Press me!'
// />
// }
// }
// }
//
// const TestableMyComponent = hook(MyComponent);
// export default TestableMyComponent;
//
// Returns the new component with the ref generating function generateTestHook as a prop.
export default function hook(WrappedComponent) {
const WrapperComponent = class extends Component {
render() {
const testHookStore = this.context;
return (
<WrappedComponent
generateTestHook={generateTestHook(testHookStore)}
{...this.props}
/>
)
}
};
// Set the context type.
WrapperComponent.contextType = TesterContext;
// Copy all non-React static methods.
hoistNonReactStatic(WrapperComponent, WrappedComponent);
// Wrap the display name for easy debugging.
WrapperComponent.displayName = `Hook(${getDisplayName(WrappedComponent)})`
return WrapperComponent;
}
function getDisplayName(WrappedComponent) {
return WrappedComponent.displayName || WrappedComponent.name || 'Component';
}