OSDN Git Service

Regular updates
[twpd/master.git] / expectjs.md
1 ---
2 title: expect.js
3 category: JavaScript libraries
4 layout: 2017/sheet
5 updated: 2017-09-02
6 weight: -1
7 ---
8
9 ### Using
10
11 ```
12 npm install --save-dev expect
13 ```
14 {: .-setup}
15
16 ```js
17 // using ES6 modules
18 import expect, { createSpy, spyOn, isSpy } from 'expect'
19 ```
20
21 ```js
22 // using CommonJS modules
23 var expect = require('expect')
24 var createSpy = expect.createSpy
25 var spyOn = expect.spyOn
26 var isSpy = expect.isSpy
27 ```
28
29 Expect is a library for assertions in tests.
30 See: [mjackson/expect](https://github.com/mjackson/expect)
31
32 ### Assertions
33
34 ```js
35 expect(x).toBe(y)
36   .toBe(val)
37   .toEqual(val)
38   .toThrow(err)
39   .toExist()          // aka: toBeTruthy()
40   .toNotExist()       // aka: toBeFalsy()
41   .toBeA(constructor)
42   .toBeA('string')
43   .toMatch(/expr/)
44   .toBeLessThan(n)
45   .toBeGreaterThan(n)
46   .toBeLessThanOrEqualTo(n)
47   .toBeGreaterThanOrEqualTo(n)
48   .toInclude(val)     // aka: toContain(val)
49   .toExclude(val)
50   .toIncludeKey(key)
51   .toExcludeKey(key)
52 ```
53
54 Also: `toNotBe`, `toNotEqual`, etc for negatives.
55
56 ### Chaining assertions
57
58 ```js
59 expect(3.14)
60   .toExist()
61   .toBeLessThan(4)
62   .toBeGreaterThan(3)
63 ```
64
65 Assertions can be chained.
66
67 ### Spies
68
69 ```js
70 const video = {
71   play: function () { ··· }
72 }
73 ```
74 {: .-setup}
75
76 ```js
77 spy = expect.spyOn(video, 'play')
78 ```
79
80 ```js
81 spy = expect.spyOn(···)
82   .andCallThrough()      // pass through
83   .andCall(fn)
84   .andThrow(exception)
85   .andReturn(value)
86 ```
87
88 ### Assertions on spies
89
90 ```js
91 expect(spy.calls.length).toEqual(1)
92 expect(spy.calls[0].context).toBe(video)
93 expect(spy.calls[0].arguments).toEqual([ 'some', 'args' ])
94 expect(spy.getLastCall().arguments).toEqual(...)
95 ```
96
97 ```js
98 expect(spy).toHaveBeenCalled()
99 expect(spy).toHaveBeenCalledWith('some', 'args')
100 ```
101
102 ### References
103
104 - <https://www.npmjs.com/package/expect>
105 - <https://github.com/mjackson/expect>