OSDN Git Service

Regular updates
[twpd/master.git] / sinon.md
1 ---
2 title: Sinon
3 category: JavaScript libraries
4 layout: 2017/sheet
5 weight: -1
6 updated: 2017-10-27
7 ---
8
9 ### Creating spies
10
11 ```js
12 fn = sinon.spy()
13 fn()
14 ```
15
16 ```js
17 fn.calledOnce == true
18 fn.callCount == 1
19 ```
20
21 ### Spying/stubbing
22
23 ```js
24 sinon.spy($, 'ajax')
25 ```
26
27 ```js
28 $.ajax();
29 $.ajax.calledOnce == true
30 ```
31
32 ```js
33 sinon.stub($, 'ajax', function () { ... }) // function optional
34 ```
35
36 ```js
37 $.ajax.calledWithMatch({ url: '/x' })
38 $.ajax.restore()
39 ```
40
41 ### Spy/stub properties
42
43 ```js
44 spy
45   .args        //=> [ [..], [..] ] one per call
46   .thisValues
47   .returnValues
48 ```
49
50 ```js
51   .called      //=> true
52   .notCalled
53   .callCount
54   .calledOnce
55   .calledTwice
56   .calledThrice
57 ```
58
59 ```js
60   .getCalls()   //=> Array
61   .getCall(0)
62   .firstCall
63 ```
64
65 ### Anonymous stub
66
67 ```js
68 stub = sinon.stub().returns(42)
69 stub() == 42
70 ```
71
72 ```js
73 stub
74   .withArgs(42).returns(1)
75   .withArgs(43).throws("TypeError")
76 ```
77
78 ```js
79 stub
80   .returns(1)
81   .throws("TypeError")
82   .returnsArg(0) // Return 1st argument
83   .callsArg(0)
84 ```
85
86 ### Fake date
87
88 ```js
89 sinon.useFakeTimers(+new Date(2011,9,1));
90 ```
91
92 ### Fake server
93
94 ```js
95 server = sinon.fakeServer.create()
96 ```
97
98 ```js
99 $.get('/file.json', ...)
100 server.requests[0].respond(
101   200,
102   { 'Content-Type': 'application/json' },
103   JSON.stringify({ hello: 'world' })
104 )
105 ```
106
107 ```js
108 server.restore()
109 ```
110
111 ### Fake XHR
112
113 ```js
114 xhr = sinon.useFakeXMLHttpRequest()
115 xhr.restore()
116 ```
117
118 ### Sandbox
119
120 ```js
121 beforeEach(function() {
122   global.sinon = require('sinon').sandbox.create()
123 })
124 ```
125
126 ```js
127 afterEach(function() {
128   global.sinon.restore()
129 })
130 ```