Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download
81152 views
1
/**
2
* Copyright 2013-2014, Facebook, Inc.
3
* All rights reserved.
4
*
5
* This source code is licensed under the BSD-style license found in the
6
* LICENSE file in the root directory of this source tree. An additional grant
7
* of patent rights can be found in the PATENTS file in the same directory.
8
*
9
* @providesModule createHierarchyRenderer
10
*/
11
12
var React = require('React');
13
14
/**
15
* Creates a render method that makes it easier to create, render, and inspect a
16
* hierarchy of mock React component classes.
17
*
18
* A component class is created for each of the supplied render methods. Each
19
* render method is invoked with the classes created using the render methods
20
* that come after it in the supplied list of render methods.
21
*
22
* var renderHierarchy = createHierarchyRenderer(
23
* function ComponentA(ComponentB, ComponentC) {...},
24
* function ComponentB(ComponentC) {...},
25
* function ComponentC() {...}
26
* );
27
*
28
* When the hierarchy is invoked, a two-dimensional array is returned. Each
29
* array corresponds to a supplied render method and contains the instances
30
* returned by that render method in the order it was invoked.
31
*
32
* var instances = renderHierarchy(
33
* function(ComponentA[, ComponentB, ComponentC]) {
34
* React.render(<ComponentA />, ...);
35
* })
36
* );
37
* instances[0][0]; // First return value of first render method.
38
* instances[1][0]; // First return value of second render method.
39
* instances[1][1]; // Second return value of second render method.
40
*
41
* Refs should be used to reference components that are not the return value of
42
* render methods.
43
*
44
* expect(instances[0][0].refs.X).toBe(...);
45
*
46
* NOTE: The component classes created for each render method are re-used for
47
* each invocation of the hierarchy renderer. If new classes are needed, you
48
* should re-execute `createHierarchyRenderer` with the same arguments.
49
*
50
* @param {array<function>} ...renderMethods
51
* @return {function}
52
*/
53
function createHierarchyRenderer(...renderMethods) {
54
var instances;
55
var Components = renderMethods.reduceRight(
56
function(Components, renderMethod, depth) {
57
var Component = React.createClass({
58
displayName: renderMethod.name,
59
render: function() {
60
instances[depth].push(this);
61
return renderMethod.apply(this, Components);
62
}
63
});
64
return [Component].concat(Components);
65
},
66
[]
67
);
68
/**
69
* @param {function} renderComponent
70
* @return {array<array<*>>}
71
*/
72
function renderHierarchy(renderComponent) {
73
instances = renderMethods.map(() => []);
74
renderComponent.apply(null, Components);
75
return instances;
76
}
77
return renderHierarchy;
78
}
79
80
module.exports = createHierarchyRenderer;
81
82