OSDN Git Service

e02d1f6aeb7975d66bf23221185b571de4ff1795
[twpd/master.git] / jest.md
1 ---
2 title: Jest
3 category: JavaScript libraries
4 layout: 2017/sheet
5 updated: 2017-09-01
6 weight: -3
7 tags: [Featurable]
8 intro: |
9   A quick overview to [Jest](https://facebook.github.io/jest/), a test framework for Node.js. This guide targets Jest v20.
10 ---
11
12 Testing
13 -------
14 {: .-three-column}
15
16 ### Quick start
17 {: .-prime}
18
19 ```bash
20 npm install --save-dev jest babel-jest
21 ```
22 {: data-line="1"}
23
24 ```js
25 /* Add to package.json */
26 "scripts": {
27   "test": "jest"
28 }
29 ```
30
31 ```bash
32 # Run your tests
33 npm test -- --watch
34 ```
35
36 See: [Getting started](http://facebook.github.io/jest/docs/en/getting-started.html)
37
38 ### Writing tests
39
40 ```js
41 describe('My work', () => {
42   test('works', () => {
43     expect(2).toEqual(2)
44   })
45 })
46 ```
47
48 See: [describe()](http://facebook.github.io/jest/docs/en/api.html#describename-fn), [test()](http://facebook.github.io/jest/docs/en/api.html#testname-fn), [expect()](http://facebook.github.io/jest/docs/en/expect.html#content)
49
50 ### BDD syntax
51
52 ```js
53 describe('My work', () => {
54   it('works', () => {
55     ···
56   })
57 })
58 ```
59
60 `it` is an alias for `test`.
61 See: [test()](http://facebook.github.io/jest/docs/en/api.html#testname-fn)
62
63 ### Setup
64
65 ```js
66 beforeEach(() => { ... })
67 afterEach(() => { ... })
68 ```
69
70 ```js
71 beforeAll(() => { ... })
72 afterAll(() => { ... })
73 ```
74
75 See: [afterAll() and more](http://facebook.github.io/jest/docs/en/api.html#afterallfn)
76
77 ### Focusing tests
78
79 ```js
80 describe.only(···)
81 it.only(···) // alias: fit()
82 ```
83
84 See: [test.only](http://facebook.github.io/jest/docs/en/api.html#testonlyname-fn)
85
86
87 ### Skipping tests
88
89 ```js
90 describe.skip(···)
91 it.skip(···) // alias: xit()
92 ```
93
94 See: [test.skip](http://facebook.github.io/jest/docs/en/api.html#testskipname-fn)
95
96 Expect
97 ------
98 {: .-three-column}
99
100 ### Basic expectations
101
102 ```js
103 expect(value)
104   .not
105   .toBe(value)
106   .toEqual(value)
107   .toBeTruthy()
108 ```
109
110 Note that `toEqual` is a deep equality check.
111 See: [expect()](http://facebook.github.io/jest/docs/en/expect.html#expectvalue)
112
113 ### Snapshots
114
115 ```js
116 expect(value)
117   .toMatchSnapshot()
118 ```
119
120 ### Errors
121
122 ```js
123 expect(value)
124   .toThrow(error)
125   .toThrowErrorMatchingSnapshot()
126 ```
127
128 ### Booleans
129
130 ```js
131 expect(value)
132   .toBeFalsy()
133   .toBeNull()
134   .toBeTruthy()
135   .toBeUndefined()
136   .toBeDefined()
137 ```
138
139 ### Numbers
140
141 ```js
142 expect(value)
143   .toBeCloseTo(number, numDigits)
144   .toBeGreaterThan(number)
145   .toBeGreaterThanOrEqual(number)
146   .toBeLessThan(number)
147   .toBeLessThanOrEqual(number)
148 ```
149
150 ### Objects
151
152 ```js
153 expect(value)
154   .toBeInstanceOf(Class)
155   .toMatchObject(object)
156   .toHaveProperty(keyPath, value)
157 ```
158
159 ### Objects
160
161 ```js
162 expect(value)
163   .toContain(item)
164   .toContainEqual(item)
165   .toHaveLength(number)
166 ```
167
168 ### Strings
169
170 ```js
171 expect(value)
172   .toMatch(regexpOrString)
173 ```
174
175 ### Others
176
177 ```js
178 expect.extend(matchers)
179 expect.any(constructor)
180 expect.addSnapshotSerializer(serializer)
181
182 expect.assertions(1)
183 ```
184
185 More features
186 -------------
187
188 ### Asynchronous tests
189
190 ```js
191 test('works with promises', () => {
192   return new Promise((resolve, reject) => {
193     ···
194   })
195 })
196 ```
197 {: data-line="2"}
198
199 ```js
200 test('works with async/await', async () => {
201   const hello = await foo()
202   ···
203 })
204 ```
205 {: data-line="2"}
206
207 Return promises, or use async/await.
208 See: [Async tutorial](http://facebook.github.io/jest/docs/en/tutorial-async.html)
209
210 ### Snapshots
211
212 ```jsx
213 it('works', () => {
214   const output = something()
215   expect(output).toMatchSnapshot()
216 })
217 ```
218 {: data-line="3"}
219
220 First run creates a snapshot. Subsequent runs match the saved snapshot.
221 See: [Snapshot testing](http://facebook.github.io/jest/docs/en/snapshot-testing.html)
222
223 ### React test renderer
224
225 ```jsx
226 import renderer from 'react-test-renderer'
227 ```
228 {: .-setup}
229
230 ```jsx
231 it('works', () => {
232   const tree = renderer.create(
233     <Link page="http://www.facebook.com">Facebook</Link>
234   ).toJSON()
235
236   expect(tree).toMatchSnapshot()
237 })
238 ```
239 {: data-line="2,3,4"}
240
241 React's test renderer can be used for Jest snapshots.
242 See: [Snapshot test](http://facebook.github.io/jest/docs/en/tutorial-react-native.html#snapshot-test)
243
244 ### Timers
245
246 ```js
247 jest.useFakeTimers()
248 ```
249
250 ```js
251 it('works', () => {
252   jest.runOnlyPendingTimers()
253   jest.runTimersToTime(1000)
254   jest.runAllTimers()
255 })
256 ```
257
258 See: [Timer Mocks](http://facebook.github.io/jest/docs/en/timer-mocks.html)
259
260 ## Mock functions
261
262 ### Mock functions
263
264 ```js
265 const fn = jest.fn()
266 ```
267
268 ```js
269 const fn = jest.fn(n => n * n)
270 ```
271
272 See: [Mock functions](http://facebook.github.io/jest/docs/en/mock-functions.html#using-a-mock-function)
273
274 ### Assertions
275
276 ```js
277 expect(fn)
278   .toHaveBeenCalled()
279   .toHaveBeenCalledTimes(number)
280   .toHaveBeenCalledWith(arg1, arg2, ...)
281   .toHaveBeenLastCalledWith(arg1, arg2, ...)
282 ```
283
284 ```js
285 expect(fn)
286   .toHaveBeenCalledWith(expect.anything())
287   .toHaveBeenCalledWith(expect.any(constructor))
288   .toHaveBeenCalledWith(expect.arrayContaining([ values ]))
289   .toHaveBeenCalledWith(expect.objectContaining({ props }))
290   .toHaveBeenCalledWith(expect.stringContaining(string))
291   .toHaveBeenCalledWith(expect.stringMatching(regexp))
292 ```
293
294 ### Instances
295
296 ```js
297 const Fn = jest.fn()
298
299 a = new Fn()
300 b = new Fn()
301 ```
302
303 ```js
304 Fn.mock.instances
305 // → [a, b]
306 ```
307 {: data-line="1"}
308
309 See: [.mock property](http://facebook.github.io/jest/docs/en/mock-functions.html#mock-property)
310
311 ### Calls
312
313 ```js
314 const fn = jest.fn()
315 fn(123)
316 fn(456)
317 ```
318
319 ```js
320 fn.mock.calls.length   // → 2
321 fn.mock.calls[0][0]    // → 123
322 fn.mock.calls[1][0]    // → 456
323 ```
324 {: data-line="1,2,3"}
325
326 See: [.mock property](http://facebook.github.io/jest/docs/en/mock-functions.html#mock-property)
327
328 ### Return values
329
330 ```js
331 const fn = jest.fn(() => 'hello')
332 ```
333
334 #### or:
335
336 ```js
337 jest.fn().mockReturnValue('hello')
338 jest.fn().mockReturnValueOnce('hello')
339 ```
340
341 ### Mock implementations
342
343 ```js
344 const fn = jest.fn()
345   .mockImplementationOnce(() => 1)
346   .mockImplementationOnce(() => 2)
347 ```
348 {: data-line="2,3"}
349
350 ```js
351 fn()    // → 1
352 fn()    // → 2
353 ```
354
355 ## References
356 {: .-one-column}
357
358 - <http://facebook.github.io/jest/>
359 {: .-also-see}