/
refs-test.js
361 lines (306 loc) · 10 KB
/
refs-test.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @emails react-core
*/
'use strict';
var React = require('React');
var ReactTestUtils = require('ReactTestUtils');
var ReactDOMFeatureFlags = require('ReactDOMFeatureFlags');
var reactComponentExpect = require('reactComponentExpect');
/**
* Counts clicks and has a renders an item for each click. Each item rendered
* has a ref of the form "clickLogN".
*/
class ClickCounter extends React.Component {
state = {count: this.props.initialCount};
triggerReset = () => {
this.setState({count: this.props.initialCount});
};
handleClick = () => {
this.setState({count: this.state.count + 1});
};
render() {
var children = [];
var i;
for (i = 0; i < this.state.count; i++) {
children.push(
<div
className="clickLogDiv"
key={'clickLog' + i}
ref={'clickLog' + i}
/>,
);
}
return (
<span className="clickIncrementer" onClick={this.handleClick}>
{children}
</span>
);
}
}
/**
* Only purpose is to test that refs are tracked even when applied to a
* component that is injected down several layers. Ref systems are difficult to
* build in such a way that ownership is maintained in an airtight manner.
*/
class GeneralContainerComponent extends React.Component {
render() {
return <div>{this.props.children}</div>;
}
}
/**
* Notice how refs ownership is maintained even when injecting a component
* into a different parent.
*/
class TestRefsComponent extends React.Component {
doReset = () => {
this.refs.myCounter.triggerReset();
};
render() {
return (
<div>
<div ref="resetDiv" onClick={this.doReset}>
Reset Me By Clicking This.
</div>
<GeneralContainerComponent ref="myContainer">
<ClickCounter ref="myCounter" initialCount={1} />
</GeneralContainerComponent>
</div>
);
}
}
/**
* Render a TestRefsComponent and ensure that the main refs are wired up.
*/
var renderTestRefsComponent = function() {
var testRefsComponent = ReactTestUtils.renderIntoDocument(
<TestRefsComponent />,
);
reactComponentExpect(testRefsComponent).toBeCompositeComponentWithType(
TestRefsComponent,
);
var generalContainer = testRefsComponent.refs.myContainer;
var counter = testRefsComponent.refs.myCounter;
reactComponentExpect(generalContainer).toBeCompositeComponentWithType(
GeneralContainerComponent,
);
reactComponentExpect(counter).toBeCompositeComponentWithType(ClickCounter);
return testRefsComponent;
};
var expectClickLogsLengthToBe = function(instance, length) {
var clickLogs = ReactTestUtils.scryRenderedDOMComponentsWithClass(
instance,
'clickLogDiv',
);
expect(clickLogs.length).toBe(length);
expect(Object.keys(instance.refs.myCounter.refs).length).toBe(length);
};
describe('reactiverefs', () => {
beforeEach(() => {
jest.resetModuleRegistry();
});
/**
* Ensure that for every click log there is a corresponding ref (from the
* perspective of the injected ClickCounter component.
*/
it('Should increase refs with an increase in divs', () => {
var testRefsComponent = renderTestRefsComponent();
var clickIncrementer = ReactTestUtils.findRenderedDOMComponentWithClass(
testRefsComponent,
'clickIncrementer',
);
expectClickLogsLengthToBe(testRefsComponent, 1);
// After clicking the reset, there should still only be one click log ref.
ReactTestUtils.Simulate.click(testRefsComponent.refs.resetDiv);
expectClickLogsLengthToBe(testRefsComponent, 1);
// Begin incrementing clicks (and therefore refs).
ReactTestUtils.Simulate.click(clickIncrementer);
expectClickLogsLengthToBe(testRefsComponent, 2);
ReactTestUtils.Simulate.click(clickIncrementer);
expectClickLogsLengthToBe(testRefsComponent, 3);
// Now reset again
ReactTestUtils.Simulate.click(testRefsComponent.refs.resetDiv);
expectClickLogsLengthToBe(testRefsComponent, 1);
});
});
/**
* Tests that when a ref hops around children, we can track that correctly.
*/
describe('ref swapping', () => {
beforeEach(() => {
jest.resetModuleRegistry();
});
class RefHopsAround extends React.Component {
state = {count: 0};
moveRef = () => {
this.setState({count: this.state.count + 1});
};
render() {
var count = this.state.count;
/**
* What we have here, is three divs with refs (div1/2/3), but a single
* moving cursor ref `hopRef` that "hops" around the three. We'll call the
* `moveRef()` function several times and make sure that the hop ref
* points to the correct divs.
*/
return (
<div>
<div
className="first"
ref={count % 3 === 0 ? 'hopRef' : 'divOneRef'}
/>
<div
className="second"
ref={count % 3 === 1 ? 'hopRef' : 'divTwoRef'}
/>
<div
className="third"
ref={count % 3 === 2 ? 'hopRef' : 'divThreeRef'}
/>
</div>
);
}
}
it('Allow refs to hop around children correctly', () => {
var refHopsAround = ReactTestUtils.renderIntoDocument(<RefHopsAround />);
var firstDiv = ReactTestUtils.findRenderedDOMComponentWithClass(
refHopsAround,
'first',
);
var secondDiv = ReactTestUtils.findRenderedDOMComponentWithClass(
refHopsAround,
'second',
);
var thirdDiv = ReactTestUtils.findRenderedDOMComponentWithClass(
refHopsAround,
'third',
);
expect(refHopsAround.refs.hopRef).toEqual(firstDiv);
expect(refHopsAround.refs.divTwoRef).toEqual(secondDiv);
expect(refHopsAround.refs.divThreeRef).toEqual(thirdDiv);
refHopsAround.moveRef();
expect(refHopsAround.refs.divOneRef).toEqual(firstDiv);
expect(refHopsAround.refs.hopRef).toEqual(secondDiv);
expect(refHopsAround.refs.divThreeRef).toEqual(thirdDiv);
refHopsAround.moveRef();
expect(refHopsAround.refs.divOneRef).toEqual(firstDiv);
expect(refHopsAround.refs.divTwoRef).toEqual(secondDiv);
expect(refHopsAround.refs.hopRef).toEqual(thirdDiv);
/**
* Make sure that after the third, we're back to where we started and the
* refs are completely restored.
*/
refHopsAround.moveRef();
expect(refHopsAround.refs.hopRef).toEqual(firstDiv);
expect(refHopsAround.refs.divTwoRef).toEqual(secondDiv);
expect(refHopsAround.refs.divThreeRef).toEqual(thirdDiv);
});
it('always has a value for this.refs', () => {
class Component extends React.Component {
render() {
return <div />;
}
}
var instance = ReactTestUtils.renderIntoDocument(<Component />);
expect(!!instance.refs).toBe(true);
});
function testRefCall() {
var refCalled = 0;
function Inner(props) {
return <a ref={props.saveA} />;
}
class Outer extends React.Component {
saveA = () => {
refCalled++;
};
componentDidMount() {
this.setState({});
}
render() {
return <Inner saveA={this.saveA} />;
}
}
ReactTestUtils.renderIntoDocument(<Outer />);
expect(refCalled).toBe(1);
}
it('ref called correctly for stateless component when __DEV__ = false', () => {
var originalDev = __DEV__;
__DEV__ = false;
testRefCall();
__DEV__ = originalDev;
});
it('ref called correctly for stateless component when __DEV__ = true', () => {
var originalDev = __DEV__;
__DEV__ = true;
testRefCall();
__DEV__ = originalDev;
});
});
describe('creating element with ref in constructor', () => {
class RefTest extends React.Component {
constructor(props) {
super(props);
this.p = <p ref="p">Hello!</p>;
}
render() {
return <div>{this.p}</div>;
}
}
var devErrorMessage =
'addComponentAsRefTo(...): Only a ReactOwner can have refs. You might ' +
"be adding a ref to a component that was not created inside a component's " +
'`render` method, or you have multiple copies of React loaded ' +
'(details: https://fb.me/react-refs-must-have-owner).';
var prodErrorMessage =
'Minified React error #119; visit ' +
'http://facebook.github.io/react/docs/error-decoder.html?invariant=119 for the full message ' +
'or use the non-minified dev environment for full errors and additional helpful warnings.';
var fiberDevErrorMessage =
'Element ref was specified as a string (p) but no owner was ' +
'set. You may have multiple copies of React loaded. ' +
'(details: https://fb.me/react-refs-must-have-owner).';
var fiberProdErrorMessage =
'Minified React error #149; visit ' +
'http://facebook.github.io/react/docs/error-decoder.html?invariant=149&args[]=p ' +
'for the full message or use the non-minified dev environment for full errors and additional ' +
'helpful warnings.';
it('throws an error when __DEV__ = true', () => {
ReactTestUtils = require('ReactTestUtils');
var originalDev = __DEV__;
__DEV__ = true;
try {
expect(function() {
ReactTestUtils.renderIntoDocument(<RefTest />);
}).toThrowError(
ReactDOMFeatureFlags.useFiber ? fiberDevErrorMessage : devErrorMessage,
);
} finally {
__DEV__ = originalDev;
}
});
it('throws an error when __DEV__ = false', () => {
ReactTestUtils = require('ReactTestUtils');
var originalDev = __DEV__;
var originalEnv = process.env.NODE_ENV;
__DEV__ = false;
process.env.NODE_ENV = 'production';
try {
expect(function() {
ReactTestUtils.renderIntoDocument(<RefTest />);
}).toThrowError(
ReactDOMFeatureFlags.useFiber
? fiberProdErrorMessage
: prodErrorMessage,
);
} finally {
__DEV__ = originalDev;
process.env.NODE_ENV = originalEnv;
}
});
});