OSDN Git Service

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