OSDN Git Service

Regular updates
[twpd/master.git] / jest.md
1 ---
2 title: Jest
3 category: JavaScript libraries
4 layout: 2017/sheet
5 updated: 2020-06-17
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
97 ### Optional flags
98
99 | Flag                  | Description                              |
100 | --------------------- | ---------------------------------------- |
101 | `--coverage`          | See a summary of test coverage           |
102 | `--detectOpenHandles` | See a summary of ports that didn't close |
103 | `--runInBand`         | Run all tests one after the other        |
104
105 Expect
106 ------
107 {: .-three-column}
108
109 ### Basic expectations
110
111 ```js
112 expect(value)
113   .not
114   .toBe(value)
115   .toEqual(value)
116   .toBeTruthy()
117 ```
118
119 Note that `toEqual` is a deep equality check.
120 See: [expect()](http://facebook.github.io/jest/docs/en/expect.html#expectvalue)
121
122 ### Snapshots
123
124 ```js
125 expect(value)
126   .toMatchSnapshot()
127   .toMatchInlineSnapshot()
128 ```
129
130 Note that `toMatchInlineSnapshot()` requires Prettier to be set up for the project.
131 See: [Inline snapshots](https://jestjs.io/docs/en/snapshot-testing#inline-snapshots)
132
133 ### Errors
134
135 ```js
136 expect(value)
137   .toThrow(error)
138   .toThrowErrorMatchingSnapshot()
139 ```
140
141 ### Booleans
142
143 ```js
144 expect(value)
145   .toBeFalsy()
146   .toBeNull()
147   .toBeTruthy()
148   .toBeUndefined()
149   .toBeDefined()
150 ```
151
152 ### Numbers
153
154 ```js
155 expect(value)
156   .toBeCloseTo(number, numDigits)
157   .toBeGreaterThan(number)
158   .toBeGreaterThanOrEqual(number)
159   .toBeLessThan(number)
160   .toBeLessThanOrEqual(number)
161 ```
162
163 ### Objects
164
165 ```js
166 expect(value)
167   .toBeInstanceOf(Class)
168   .toMatchObject(object)
169   .toHaveProperty(keyPath, value)
170 ```
171
172 ### Objects
173
174 ```js
175 expect(value)
176   .toContain(item)
177   .toContainEqual(item)
178   .toHaveLength(number)
179 ```
180
181 ### Strings
182
183 ```js
184 expect(value)
185   .toMatch(regexpOrString)
186 ```
187
188 ### Others
189
190 ```js
191 expect.extend(matchers)
192 expect.any(constructor)
193 expect.addSnapshotSerializer(serializer)
194
195 expect.assertions(1)
196 ```
197
198 More features
199 -------------
200
201 ### Asynchronous tests
202
203 ```js
204 test('works with promises', () => {
205   return new Promise((resolve, reject) => {
206     ···
207   })
208 })
209 ```
210 {: data-line="2"}
211
212 ```js
213 test('works with async/await', async () => {
214   const hello = await foo()
215   ···
216 })
217 ```
218 {: data-line="2"}
219
220 Return promises, or use async/await.
221 See: [Async tutorial](http://facebook.github.io/jest/docs/en/tutorial-async.html)
222
223 ### Snapshots
224
225 ```jsx
226 it('works', () => {
227   const output = something()
228   expect(output).toMatchSnapshot()
229 })
230 ```
231 {: data-line="3"}
232
233 First run creates a snapshot. Subsequent runs match the saved snapshot.
234 See: [Snapshot testing](http://facebook.github.io/jest/docs/en/snapshot-testing.html)
235
236 ### React test renderer
237
238 ```jsx
239 import renderer from 'react-test-renderer'
240 ```
241 {: .-setup}
242
243 ```jsx
244 it('works', () => {
245   const tree = renderer.create(
246     <Link page="http://www.facebook.com">Facebook</Link>
247   ).toJSON()
248
249   expect(tree).toMatchSnapshot()
250 })
251 ```
252 {: data-line="2,3,4"}
253
254 React's test renderer can be used for Jest snapshots.
255 See: [Snapshot test](http://facebook.github.io/jest/docs/en/tutorial-react-native.html#snapshot-test)
256
257 ### Timers
258
259 ```js
260 jest.useFakeTimers()
261 ```
262
263 ```js
264 it('works', () => {
265   jest.runOnlyPendingTimers()
266   jest.runTimersToTime(1000)
267   jest.runAllTimers()
268 })
269 ```
270
271 See: [Timer Mocks](http://facebook.github.io/jest/docs/en/timer-mocks.html)
272
273 ## Mock functions
274
275 ### Mock functions
276
277 ```js
278 const fn = jest.fn()
279 ```
280
281 ```js
282 const fn = jest.fn(n => n * n)
283 ```
284
285 See: [Mock functions](http://facebook.github.io/jest/docs/en/mock-functions.html#using-a-mock-function)
286
287 ### Assertions
288
289 ```js
290 expect(fn)
291   .toHaveBeenCalled()
292   .toHaveBeenCalledTimes(number)
293   .toHaveBeenCalledWith(arg1, arg2, ...)
294   .toHaveBeenLastCalledWith(arg1, arg2, ...)
295 ```
296
297 ```js
298 expect(fn)
299   .toHaveBeenCalledWith(expect.anything())
300   .toHaveBeenCalledWith(expect.any(constructor))
301   .toHaveBeenCalledWith(expect.arrayContaining([ values ]))
302   .toHaveBeenCalledWith(expect.objectContaining({ props }))
303   .toHaveBeenCalledWith(expect.stringContaining(string))
304   .toHaveBeenCalledWith(expect.stringMatching(regexp))
305 ```
306
307 ### Instances
308
309 ```js
310 const Fn = jest.fn()
311
312 a = new Fn()
313 b = new Fn()
314 ```
315
316 ```js
317 Fn.mock.instances
318 // → [a, b]
319 ```
320 {: data-line="1"}
321
322 See: [.mock property](http://facebook.github.io/jest/docs/en/mock-functions.html#mock-property)
323
324 ### Calls
325
326 ```js
327 const fn = jest.fn()
328 fn(123)
329 fn(456)
330 ```
331
332 ```js
333 fn.mock.calls.length   // → 2
334 fn.mock.calls[0][0]    // → 123
335 fn.mock.calls[1][0]    // → 456
336 ```
337 {: data-line="1,2,3"}
338
339 See: [.mock property](http://facebook.github.io/jest/docs/en/mock-functions.html#mock-property)
340
341 ### Return values
342
343 ```js
344 const fn = jest.fn(() => 'hello')
345 ```
346
347 #### or:
348
349 ```js
350 jest.fn().mockReturnValue('hello')
351 jest.fn().mockReturnValueOnce('hello')
352 ```
353
354 ### Mock implementations
355
356 ```js
357 const fn = jest.fn()
358   .mockImplementationOnce(() => 1)
359   .mockImplementationOnce(() => 2)
360 ```
361 {: data-line="2,3"}
362
363 ```js
364 fn()    // → 1
365 fn()    // → 2
366 ```
367
368 ## References
369 {: .-one-column}
370
371 - <http://facebook.github.io/jest/>
372 {: .-also-see}