OSDN Git Service

Regular updates
[twpd/master.git] / enzyme.md
1 ---
2 title: Enzyme
3 category: React
4 layout: 2017/sheet
5 updated: 2018-04-27
6 tags: [Featured]
7 weight: -1
8 keywords:
9   - shallow()
10   - mount()
11   - wrap.setProps()
12   - "wrap.find().simulate('click')"
13   - "wrap.contains(<div/>)"
14 intro: |
15   [Enzyme](http://airbnb.io/enzyme) lets you write unit tests for React components. This guide covers Enzyme 3.x.
16 ---
17
18 ## Getting started
19
20 ### Mounting
21 {: .-prime}
22
23 ```js
24 import {shallow, mount} from 'enzyme'
25 ```
26 {: .-setup}
27
28 ```js
29 wrap = shallow(<MyComponent />)
30 ```
31
32 ```js
33 wrap = mount(<MyComponent />)
34 ```
35
36 Shallow wrapping doesn't descend down to sub-components.
37 A full mount also mounts sub-components.
38
39 See: [Shallow rendering](http://airbnb.io/enzyme/docs/api/shallow.html),
40 [Full rendering](http://airbnb.io/enzyme/docs/api/mount.html)
41
42 ### Debugging
43
44 ```js
45 console.log(wrap.debug())
46 ```
47
48 Shows HTML for debugging purposes.
49
50 See: [debug()](http://airbnb.io/enzyme/docs/api/ReactWrapper/debug.html)
51
52 ## Examples
53 {: .-three-column}
54
55 ### Basic example
56 {: .-prime}
57
58 ```js
59 import { shallow } from 'enzyme'
60 import MyComponent from '../MyComponent'
61 ```
62 {: .-setup}
63
64 ```js
65 it('works', () => {
66   const wrap = shallow(
67     <MyComponent name='Groot' />
68   )
69
70   expect(wrap.text()).toEqual('I am Groot')
71 })
72 ```
73
74 ### Props and state
75
76 #### Setting
77
78 ```js
79 wrap.setProps({ name: 'Moe' })
80 wrap.setState({ show: true })
81 ```
82
83 #### Asserting
84
85 ```js
86 expect(wrap.prop('name')).toEqual('Moe')
87 expect(wrap.state('show')).toEqual(true)
88 ```
89
90 ```js
91 expect('name' in wrap.props()).toEqual('Moe')
92 expect('show' in wrap.state()).toEqual(true)
93 ```
94
95 ### Matching elements
96
97 ```js
98 expect(
99   wrap.containsMatchingElement(
100     <span>I am groot</span>
101   )
102 ).toBeTruthy()
103 ```
104
105 `containsMatchingElement()` is probably the most useful assertion in Jest.
106
107 ### Snapshots
108
109 ```js
110 expect(wrap).toMatchSnapshot()
111 ```
112
113 Be sure you've set up enzyme-to-json for snapshots (see [Installing](#installing) below).
114
115 ### Traversions
116
117 ```js
118 expect(
119   wrap.find('button').text()
120 ).toEqual('Submit')
121 ```
122
123 Use `.find()` to traverse down to nodes. It will return wrapper objects, too.
124
125 ### Simulating events
126
127 ```js
128 wrap.find('input').simulate('click')
129 ```
130
131 #### With event object props
132
133 ```js
134 wrap.find('input').simulate('change', {
135   target: { value: 'hello' }
136 })
137 ```
138
139 ## Installing
140
141 ### Initial setup
142
143 ```
144 npm install --save-dev enzyme \
145   enzyme-adapter-react-16 \
146   react-test-renderer
147 ```
148 {: .-setup}
149
150 #### test/setup.js
151
152 ```js
153 import Enzyme from 'enzyme'
154 import Adapter from 'enzyme-adapter-react-16'
155
156 Enzyme.configure({ adapter: new Adapter() })
157 ```
158
159 #### package.json
160
161 ```js
162 "jest": {
163   "setupFiles": [
164     "test/setup.js"
165   ]
166 }
167 ```
168
169 This configures Enzyme for React v16, and Jest to automatically configure Enzyme for you. There are other adapters in Enzyme's installation instructions.
170
171 See: [Installation](http://airbnb.io/enzyme/#installation)
172
173 ### Jest snapshots
174
175 ```
176 npm install --save-dev enzyme-to-json
177 ```
178 {: .-setup}
179
180 #### package.json
181
182 ```js
183 "jest": {
184   "snapshotSerializers": [
185     "enzyme-to-json/serializer"
186   ]
187 }
188 ```
189
190 #### Test
191
192 ```js
193 it('works', () => {
194   wrap = mount(<MyComponent />)
195   expect(wrap).toMatchSnapshot()
196 })
197 ```
198
199 Optional, but recommended: This allows you to use Enzyme wrappers with Jest snapshots.
200
201 See: [enzyme-to-json](https://www.npmjs.com/package/enzyme-to-json)
202
203 ## ReactWrapper
204
205 ### Traversing
206
207 ```js
208 wrap.find('button')   // → ReactWrapper
209 wrap.filter('button') // → ReactWrapper
210 wrap.not('span')      // → ReactWrapper (inverse of filter())
211 wrap.children()       // → ReactWrapper
212 wrap.parent()         // → ReactWrapper
213 wrap.closest('div')   // → ReactWrapper
214 wrap.childAt(0)       // → ReactWrapper
215 wrap.at(0)            // → ReactWrapper
216 wrap.first()          // → ReactWrapper
217 wrap.last()           // → ReactWrapper
218 ```
219
220 ```js
221 wrap.get(0)           // → ReactElement
222 wrap.getElement()     // → ReactElement
223 wrap.getElements()    // → Array<ReactElement>
224 wrap.getDOMNode()     // → DOMComponent
225 ```
226
227 See: [Full rendering API](http://airbnb.io/enzyme/docs/api/mount.html)
228
229 ### Actions
230
231 ```js
232 wrap.simulate('click')
233 ```
234
235 ### React components
236
237 ```js
238 wrap.setState({ ··· })
239 wrap.setProps({ ··· })
240 wrap.setContext({ ··· })
241 ```
242
243 ```js
244 wrap.state()         // get full state
245 wrap.props()         // get full props
246 wrap.context()       // get full context
247 ```
248
249 ```js
250 wrap.state('key')    // → any
251 wrap.prop('key')     // → any
252 wrap.context('key')  // → any
253 ```
254
255 ```js
256 wrap.instance()      // → ReactComponent
257 ```
258
259 ### Mount
260
261 ```js
262 wrap.mount()
263 wrap.unmount()
264 wrap.update()      // calls forceUpdate()
265 ```
266
267 ### Tests
268
269 ```js
270 wrap.debug()               // → string
271 wrap.html()                // → string
272 wrap.text()                // → string
273 wrap.type()                // → string | function
274 wrap.name()                // → string
275 wrap.is('.classname')      // → boolean
276 wrap.hasClass('class')     // → boolean
277 wrap.exists()              // → boolean
278 wrap.contains(<div />)     // → boolean
279 wrap.contains([ <div /> ]) // → boolean
280 wrap.some('.child')        // → boolean
281
282 wrap.someWhere(n => n.hasClass('foo'))
283
284 wrap.containsMatchingElement(<div />)         // → boolean
285 wrap.containsAllMatchingElements([ <div /> ]) // → boolean
286 wrap.containsAnyMatchingElements([ <div /> ]) // → boolean
287 ```
288
289 ## References
290
291 - [Enzyme website](https://airbnb.io/enzyme) _(airbnb.io)_
292 - [Enzyme v2 cheatsheet](./enzyme@2) _(devhints.io)_ (old version)