/
instance.md
61 lines (43 loc) · 1.41 KB
/
instance.md
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
# `.instance() => ReactComponent`
Returns the single-node wrapper's node's underlying class instance; `this` in its methods. It must be a single-node wrapper.
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.
#### Returns
`ReactComponent|DOMComponent`: The retrieved instance.
#### Example
<!-- eslint react/prop-types: 0, react/prefer-stateless-function: 0 -->
```jsx
function SFC() {
return <div>MyFunction</div>;
}
class Stateful extends React.Component {
render() {
return <div>MyClass</div>;
}
}
```
#### React 16.x
```jsx
test('wrapper instance is null', () => {
const wrapper = mount(<SFC />);
const instance = wrapper.instance();
expect(instance).to.equal(null);
});
test('wrapper instance is not null', () => {
const wrapper = mount(<Stateful />);
const instance = wrapper.instance();
expect(instance).to.be.instanceOf(MyCStatefullass);
});
```
#### React 15.x
```jsx
test('wrapper instance is not null', () => {
const wrapper = mount(<SFC />);
const instance = wrapper.instance();
expect(instance).to.be.instanceOf(SFC);
});
test('wrapper instance is not null', () => {
const wrapper = mount(<Stateful />);
const instance = wrapper.instance();
expect(instance).to.be.instanceOf(Stateful);
});
```