|
1 | 1 | # `.instance() => ReactComponent` |
2 | 2 |
|
3 | | -Returns the single-node wrapper's node's underlying class instance; `this` in its methods. |
4 | | - |
5 | | -NOTE: can only be called on a wrapper instance that is also the root instance. With React `16` and above, `instance()` returns `null` for stateless functional components. |
| 3 | +Returns the single-node wrapper's node's underlying class instance; `this` in its methods. It must be a single-node wrapper. |
6 | 4 |
|
| 5 | +NOTE: can only be called on a wrapper instance that is also the root instance. With React `16` and above, `instance()` returns `null` for functional components, regardless of [hooks](https://reactjs.org/docs/hooks-intro.html) usage. |
7 | 6 |
|
8 | 7 | #### Returns |
9 | 8 |
|
10 | 9 | `ReactComponent|DOMComponent`: The retrieved instance. |
11 | 10 |
|
12 | | - |
13 | 11 | #### Example |
14 | 12 |
|
15 | 13 | <!-- eslint react/prop-types: 0, react/prefer-stateless-function: 0 --> |
| 14 | + |
16 | 15 | ```jsx |
17 | | -function Stateless() { |
18 | | - return <div>Stateless</div>; |
| 16 | +function SFC() { |
| 17 | + return <div>MyFunction</div>; |
19 | 18 | } |
20 | 19 |
|
21 | 20 | class Stateful extends React.Component { |
22 | 21 | render() { |
23 | | - return <div>Stateful</div>; |
| 22 | + return <div>MyClass</div>; |
24 | 23 | } |
25 | 24 | } |
26 | 25 | ``` |
27 | 26 |
|
28 | 27 | #### React 16.x |
| 28 | + |
29 | 29 | ```jsx |
30 | | -test('shallow wrapper instance should be null', () => { |
31 | | - const wrapper = shallow(<Stateless />); |
| 30 | +test('wrapper instance is null', () => { |
| 31 | + const wrapper = shallow(<SFC />); |
32 | 32 | const instance = wrapper.instance(); |
33 | 33 |
|
34 | 34 | expect(instance).to.equal(null); |
35 | 35 | }); |
36 | 36 |
|
37 | | -test('shallow wrapper instance should not be null', () => { |
| 37 | +test('wrapper instance is not null', () => { |
38 | 38 | const wrapper = shallow(<Stateful />); |
39 | 39 | const instance = wrapper.instance(); |
40 | 40 |
|
41 | | - expect(instance).to.be.instanceOf(Stateful); |
| 41 | + expect(instance).to.be.instanceOf(MyCStatefullass); |
42 | 42 | }); |
43 | 43 | ``` |
44 | 44 |
|
45 | 45 | #### React 15.x |
| 46 | + |
46 | 47 | ```jsx |
47 | | -test('shallow wrapper instance should not be null', () => { |
48 | | - const wrapper = shallow(<Stateless />); |
| 48 | +test('wrapper instance is not null', () => { |
| 49 | + const wrapper = shallow(<SFC />); |
49 | 50 | const instance = wrapper.instance(); |
50 | 51 |
|
51 | | - expect(instance).to.be.instanceOf(Stateless); |
| 52 | + expect(instance).to.be.instanceOf(SFC); |
52 | 53 | }); |
53 | 54 |
|
54 | | -test('shallow wrapper instance should not be null', () => { |
| 55 | +test('wrapper instance is not null', () => { |
55 | 56 | const wrapper = shallow(<Stateful />); |
56 | 57 | const instance = wrapper.instance(); |
57 | 58 |
|
|
0 commit comments