-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathjsmockito.js
925 lines (853 loc) · 26.3 KB
/
jsmockito.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
/* vi:ts=2 sw=2 expandtab
*
* JsMockito v1.0.3
* http://github.com/chrisleishman/jsmockito
*
* Mockito port to JavaScript
*
* Copyright (c) 2009 Chris Leishman
* Licensed under the BSD license
*/
/**
* Main namespace.
* @namespace
*
* <h2>Contents</h2>
*
* <ol>
* <li><a href="#1">Let's verify some behaviour!</a></li>
* <li><a href="#2">How about some stubbing?</a></li>
* <li><a href="#3">Matching Arguments</a></li>
* <li><a href="#4">Verifying exact number of invocations / at least once /
* never</a></li>
* <li><a href="#5">Matching the context ('this')</a></li>
* <li><a href="#6">Making sure interactions never happened on a mock</a></li>
* <li><a href="#7">Finding redundant invocations</a></li>
* </ol>
*
* <p>In the following examples object mocking is done with Array as this is
* well understood, although you probably wouldn't mock this in normal test
* development.</p>
*
* <h2><a name="1">1. Let's verify some behaviour!</a></h2>
*
* <p>For an object:</p>
* <pre>
* //mock creation
* var mockedArray = mock(Array);
*
* //using mock object
* mockedArray.push("one");
* mockedArray.reverse();
*
* //verification
* verify(mockedArray).push("one");
* verify(mockedArray).reverse();
* </pre>
*
* <p>For a function:</p>
* <pre>
* //mock creation
* var mockedFunc = mockFunction();
*
* //using mock function
* mockedFunc('hello world');
* mockedFunc.call(this, 'foobar');
* mockedFunc.apply(this, [ 'barfoo' ]);
*
* //verification
* verify(mockedFunc)('hello world');
* verify(mockedFunc)('foobar');
* verify(mockedFunc)('barfoo');
* </pre>
*
* <p>Once created a mock will remember all interactions. Then you selectively
* verify whatever interactions you are interested in.</p>
*
* <h2><a name="2">2. How about some stubbing?</a></h2>
*
* <p>For an object:</p>
* <pre>
* var mockedArray = mock(Array);
*
* //stubbing
* when(mockedArray).slice(0).thenReturn('f');
* when(mockedArray).slice(1).thenThrow('An exception');
*
* //following returns "f"
* mockedArray.slice(0);
*
* //following throws exception 'An exception'
* mockedArray.slice(1);
*
* //following returns undefined as slice(999) was not stubbed
* mockedArray.slice(999);
*
* //can also verify a stubbed invocation, although this is usually redundant
* verify(mockedArray).slice(0);
* </pre>
*
* <p>For a function:</p>
* <pre>
* var mockedFunc = mockFunction();
*
* //stubbing
* when(mockedFunc)(0).thenReturn('f');
* when(mockedFunc)(1).thenThrow('An exception');
*
* //following returns "f"
* mockedFunc(0);
*
* //following throws exception 'An exception'
* mockedFunc(1);
*
* //following returns undefined as mockedFunc(999) was not stubbed
* mockedFunc(999)
*
* //can also verify a stubbed invocation, although this is usually redundant
* verify(mockedFunc)(0);
* </pre>
*
* <ul>
* <li>By default mocks return undefined from all invocations;</li>
* <li>Stubs can be overwritten;</li>
* <li>Once stubbed, the method will always return the stubbed value regardless
* of how many times it is called;</li>
* <li>Last stubbing is more important - when you stubbed the same method with
* the same (or overlapping) matchers many times.</li>
* </ul>
*
* <h2><a name="3">3. Matching Arguments</a></h2>
*
* <p>JsMockito verifies arguments using
* <a href="http://jshamcrest.destaquenet.com/">JsHamcrest</a> matchers.
*
* <pre>
* var mockedArray = mock(Array);
* var mockedFunc = mockFunction();
*
* //stubbing using JsHamcrest
* when(mockedArray).slice(lessThan(10)).thenReturn('f');
* when(mockedFunc)(containsString('world')).thenReturn('foobar');
*
* //following returns "f"
* mockedArray.slice(5);
*
* //following returns "foobar"
* mockedFunc('hello world');
*
* //you can also use matchers in verification
* verify(mockedArray).slice(greaterThan(4));
* verify(mockedFunc)(equalTo('hello world'));
*
* //if not specified then the matcher is anything(), thus either of these
* //will match an invocation with a single argument
* verify(mockedFunc)();
* verify(mockedFunc)(anything());
* </pre>
*
* <ul>
* <li>If the argument provided during verification/stubbing is not a
* JsHamcrest matcher, then 'equalTo(arg)' is used instead;</li>
* <li>Where a function/method was invoked with an argument, but the stub or
* verification does not provide a matcher, then anything() is assumed;</li>
* <li>The reverse, however, is not true - the anything() matcher will
* <em>not</em> match an argument that was never provided.</li>
* </ul>
*
* <h2><a name="4">4. Verifying exact number of invocations / at least once /
* never</a></h2>
*
* <pre>
* var mockedArray = mock(Array);
* var mockedFunc = mockFunction();
*
* mockedArray.slice(5);
* mockedArray.slice(6);
* mockedFunc('a');
* mockedFunc('b');
*
* //verification of multiple matching invocations
* verify(mockedArray, times(2)).slice(anything());
* verify(mockedFunc, times(2))(anything());
*
* //the default is times(1), making these are equivalent
* verify(mockedArray, times(1)).slice(5);
* verify(mockedArray).slice(5);
* </pre>
*
* <h2><a name="5">5. Matching the context ('this')</a></h2>
*
* Functions can be invoked with a specific context, using the 'call' or
* 'apply' methods. JsMockito mock functions (and mock object methods)
* will remember this context and verification/stubbing can match on it.
*
* <p>For a function:</p>
* <pre>
* var mockedFunc = mockFunction();
* var context1 = {};
* var context2 = {};
*
* when(mockedFunc).call(equalTo(context2), anything()).thenReturn('hello');
*
* mockedFunc.call(context1, 'foo');
* //the following returns 'hello'
* mockedFunc.apply(context2, [ 'bar' ]);
*
* verify(mockedFunc).apply(context1, [ 'foo' ]);
* verify(mockedFunc).call(context2, 'bar');
* </pre>
*
* <p>For object method invocations, the context is usually the object itself.
* But sometimes people do strange things, and you need to test it - so
* the same approach can be used for an object:</p>
* <pre>
* var mockedArray = mock(Array);
* var otherContext = {};
*
* when(mockedArray).slice.call(otherContext, 5).thenReturn('h');
*
* //the following returns 'h'
* mockedArray.slice.apply(otherContext, [ 5 ]);
*
* verify(mockedArray).slice.call(equalTo(otherContext), 5);
* </pre>
*
* <ul>
* <li>For mock functions, the default context matcher is anything();</li>
* <li>For mock object methods, the default context matcher is
* sameAs(mockObj).</li>
* </ul>
*
* <h2><a name="6">6. Making sure interactions never happened on a mock</a></h2>
*
* <pre>
* var mockOne = mock(Array);
* var mockTwo = mock(Array);
* var mockThree = mockFunction();
*
* //only mockOne is interacted with
* mockOne.push(5);
*
* //verify a method was never called
* verify(mockOne, never()).unshift('a');
*
* //verify that other mocks were not interacted with
* verifyZeroInteractions(mockTwo, mockThree);
* </pre>
*
* <h2><a name="7">7. Finding redundant invocations</a></h2>
*
* <pre>
* var mockArray = mock(Array);
*
* mockArray.push(5);
* mockArray.push(8);
*
* verify(mockArray).push(5);
*
* // following verification will fail
* verifyNoMoreInteractions(mockArray);
* </pre>
*/
JsMockito = {
/**
* Library version,
*/
version: '1.0.3',
_export: ['isMock', 'when', 'verify', 'verifyZeroInteractions',
'verifyNoMoreInteractions', 'spy'],
/**
* Test if a given variable is a mock
*
* @param maybeMock An object
* @return {boolean} true if the variable is a mock
*/
isMock: function(maybeMock) {
return typeof maybeMock._jsMockitoVerifier != 'undefined';
},
/**
* Add a stub for a mock object method or mock function
*
* @param mock A mock object or mock anonymous function
* @return {object or function} A stub builder on which the method or
* function to be stubbed can be invoked
*/
when: function(mock) {
return mock._jsMockitoStubBuilder();
},
/**
* Verify that a mock object method or mock function was invoked
*
* @param mock A mock object or mock anonymous function
* @param verifier Optional JsMockito.Verifier instance (default: JsMockito.Verifiers.once())
* @return {object or function} A verifier on which the method or function to
* be verified can be invoked
*/
verify: function(mock, verifier) {
return (verifier || JsMockito.Verifiers.once()).verify(mock);
},
/**
* Verify that no mock object methods or the mock function were ever invoked
*
* @param mock A mock object or mock anonymous function (multiple accepted)
*/
verifyZeroInteractions: function() {
JsMockito.each(arguments, function(mock) {
JsMockito.Verifiers.zeroInteractions().verify(mock);
});
},
/**
* Verify that no mock object method or mock function invocations remain
* unverified
*
* @param mock A mock object or mock anonymous function (multiple accepted)
*/
verifyNoMoreInteractions: function() {
JsMockito.each(arguments, function(mock) {
JsMockito.Verifiers.noMoreInteractions().verify(mock);
});
},
/**
* Create a mock that proxies a real function or object. All un-stubbed
* invocations will be passed through to the real implementation, but can
* still be verified.
*
* @param {object or function} delegate A 'real' (concrete) object or
* function that the mock will delegate unstubbed invocations to
* @return {object or function} A mock object (as per mock) or mock function
* (as per mockFunction)
*/
spy: function(delegate) {
return (typeof delegate == 'function')?
JsMockito.mockFunction(delegate) : JsMockito.mock(delegate);
},
contextCaptureFunction: function(defaultContext, handler) {
// generate a function with overridden 'call' and 'apply' methods
// and apply a default context when these are not used to supply
// one explictly.
var captureFunction = function() {
return captureFunction.apply(defaultContext,
Array.prototype.slice.call(arguments, 0));
};
captureFunction.call = function(context) {
return captureFunction.apply(context,
Array.prototype.slice.call(arguments, 1));
};
captureFunction.apply = function(context, args) {
return handler.apply(this, [ context, args||[] ]);
};
return captureFunction;
},
matchArray: function(matchers, array) {
if (matchers.length > array.length)
return false;
return !JsMockito.any(matchers, function(matcher, i) {
return !matcher.matches(array[i]);
});
},
toMatcher: function(obj) {
return JsHamcrest.isMatcher(obj)? obj :
JsHamcrest.Matchers.equalTo(obj);
},
mapToMatchers: function(array) {
return JsMockito.map(array, function(obj) {
return JsMockito.toMatcher(obj);
});
},
each: function(array, callback) {
if (array.length == undefined) {
for (var key in array)
callback(array[key], key);
} else {
for (var i = 0; i < array.length; i++)
callback(array[i], i);
}
},
map: function(array, callback) {
var result = [];
JsMockito.each(array, function(elem, key) {
var val = callback(elem, key);
if (val != null)
result.push(val);
});
return result;
},
grep: function(array, callback) {
var result = [];
JsMockito.each(array, function(elem, key) {
if (callback(elem, key))
result.push(elem);
});
return result;
},
find: function(array, callback) {
for (var i = 0; i < array.length; i++)
if (callback(array[i], i))
return array[i];
return undefined;
},
any: function(array, callback) {
return (this.find(array, callback) != undefined);
},
extend: function(dstObject, srcObject) {
for (var prop in srcObject) {
dstObject[prop] = srcObject[prop];
}
return dstObject;
},
verifier: function(name, proto) {
JsMockito.Verifiers[name] = function() { JsMockito.Verifier.apply(this, arguments) };
JsMockito.Verifiers[name].prototype = new JsMockito.Verifier;
JsMockito.Verifiers[name].prototype.constructor = JsMockito.Verifiers[name];
JsMockito.extend(JsMockito.Verifiers[name].prototype, proto);
}
};
/**
* Create a mockable and stubbable anonymous function.
*
* <p>Once created, the function can be invoked and will return undefined for
* any interactions that do not match stub declarations.</p>
*
* <pre>
* var mockFunc = JsMockito.mockFunction();
* JsMockito.when(mockFunc).call(anything(), 1, 5).thenReturn(6);
* mockFunc(1, 5); // result is 6
* JsMockito.verify(mockFunc)(1, greaterThan(2));
* </pre>
*
* @param funcName {string} The name of the mock function to use in messages
* (defaults to 'func')
* @param delegate {function} The function to delegate unstubbed calls to
* (optional)
* @return {function} an anonymous function
*/
JsMockito.mockFunction = function(funcName, delegate) {
if (typeof funcName == 'function') {
delegate = funcName;
funcName = undefined;
}
funcName = funcName || 'func';
delegate = delegate || function() { };
var stubMatchers = []
var interactions = [];
var mockFunc = function() {
var args = [this];
args.push.apply(args, arguments);
interactions.push({args: args});
var stubMatcher = JsMockito.find(stubMatchers, function(stubMatcher) {
return JsMockito.matchArray(stubMatcher[0], args);
});
if (stubMatcher == undefined)
return delegate.apply(this, arguments);
var stubs = stubMatcher[1];
if (stubs.length == 0)
return undefined;
var stub = stubs[0];
if (stubs.length > 1)
stubs.shift();
return stub.apply(this, arguments);
};
mockFunc.prototype = delegate.prototype;
mockFunc._jsMockitoStubBuilder = function(contextMatcher) {
var contextMatcher = contextMatcher || JsHamcrest.Matchers.anything();
return matcherCaptureFunction(contextMatcher, function(matchers) {
var stubMatch = [matchers, []];
stubMatchers.push(stubMatch);
return {
then: function() {
stubMatch[1].push.apply(stubMatch[1], arguments);
return this;
},
thenReturn: function() {
this.then.apply(this, JsMockito.map(arguments, function(value) {
return function() { return value };
}));
},
thenThrow: function(exception) {
this.then.apply(this, JsMockito.map(arguments, function(value) {
return function() { throw value };
}));
}
};
});
};
mockFunc._jsMockitoVerifier = function(verifier, contextMatcher) {
var contextMatcher = contextMatcher || JsHamcrest.Matchers.anything();
return matcherCaptureFunction(contextMatcher, function(matchers) {
return verifier(funcName, interactions, matchers, matchers[0] != contextMatcher);
});
};
mockFunc._jsMockitoMockFunctions = function() {
return [ mockFunc ];
};
return mockFunc;
function matcherCaptureFunction(contextMatcher, handler) {
return JsMockito.contextCaptureFunction(contextMatcher,
function(context, args) {
var matchers = JsMockito.mapToMatchers([context].concat(args || []));
return handler(matchers);
}
);
};
};
JsMockito._export.push('mockFunction');
/**
* Create a mockable and stubbable objects.
*
* <p>A mock is created with the constructor for an object as an argument.
* Once created, the mock object will have all the same methods as the source
* object which, when invoked, will return undefined by default.</p>
*
* <p>Stub declarations may then be made for these methods to have them return
* useful values or perform actions when invoked.</p>
*
* <pre>
* MyObject = function() {
* this.add = function(a, b) { return a + b }
* };
*
* var mockObj = JsMockito.mock(MyObject);
* mockObj.add(5, 4); // result is undefined
*
* JsMockito.when(mockFunc).add(1, 2).thenReturn(6);
* mockObj.add(1, 2); // result is 6
*
* JsMockito.verify(mockObj).add(1, greaterThan(2)); // ok
* JsMockito.verify(mockObj).add(1, equalTo(2)); // ok
* JsMockito.verify(mockObj).add(1, 4); // will throw an exception
* </pre>
*
* @param Obj {function} the constructor for the object to be mocked
* @return {object} a mock object
*/
JsMockito.mock = function(Obj) {
var delegate = {};
if (typeof Obj != "function") {
delegate = Obj;
Obj = function() { };
Obj.prototype = delegate;
Obj.prototype.constructor = Obj;
}
var MockObject = function() { };
MockObject.prototype = new Obj;
MockObject.prototype.constructor = MockObject;
var mockObject = new MockObject();
var stubBuilders = {};
var verifiers = {};
var contextMatcher = JsHamcrest.Matchers.sameAs(mockObject);
var addMockMethod = function(name) {
var delegateMethod;
if (delegate[name] != undefined) {
delegateMethod = function() {
var scope = (this == mockObject)? delegate : this;
return delegate[name].apply(scope, arguments);
};
}
mockObject[name] = JsMockito.mockFunction('obj.' + name, delegateMethod);
stubBuilders[name] = mockObject[name]._jsMockitoStubBuilder;
verifiers[name] = mockObject[name]._jsMockitoVerifier;
};
for (var methodName in mockObject) {
if (methodName != 'constructor')
addMockMethod(methodName);
}
for (var typeName in JsMockito.nativeTypes) {
if (mockObject instanceof JsMockito.nativeTypes[typeName].type) {
for (var i = 0; i < JsMockito.nativeTypes[typeName].methods.length; ++i) {
addMockMethod(JsMockito.nativeTypes[typeName].methods[i]);
}
}
}
mockObject._jsMockitoStubBuilder = function() {
var stubBuilderObject = new MockObject();
for (var name in stubBuilders) {
stubBuilderObject[name] = stubBuilders[name].call(this, contextMatcher);
}
return stubBuilderObject;
};
mockObject._jsMockitoVerifier = function(verifier) {
var verifierObject = new MockObject();
for (var name in verifiers) {
verifierObject[name] = verifiers[name].call(this, verifier, contextMatcher);
}
return verifierObject;
};
mockObject._jsMockitoMockFunctions = function() {
return JsMockito.map(mockObject, function(func) {
return JsMockito.isMock(func)? func : null;
});
};
return mockObject;
};
JsMockito._export.push('mock');
JsMockito.nativeTypes = {
'Array': {
type: Array,
methods: [
'concat', 'join', 'pop', 'push', 'reverse', 'shift', 'slice', 'sort',
'splice', 'toString', 'unshift', 'valueOf'
]
},
'Boolean': {
type: Boolean,
methods: [
'toString', 'valueOf'
]
},
'Date': {
type: Date,
methods: [
'getDate', 'getDay', 'getFullYear', 'getHours', 'getMilliseconds',
'getMinutes', 'getMonth', 'getSeconds', 'getTime', 'getTimezoneOffset',
'getUTCDate', 'getUTCDay', 'getUTCMonth', 'getUTCFullYear',
'getUTCHours', 'getUTCMinutes', 'getUTCSeconds', 'getUTCMilliseconds',
'getYear', 'setDate', 'setFullYear', 'setHours', 'setMilliseconds',
'setMinutes', 'setMonth', 'setSeconds', 'setTime', 'setUTCDate',
'setUTCMonth', 'setUTCFullYear', 'setUTCHours', 'setUTCMinutes',
'setUTCSeconds', 'setUTCMilliseconds', 'setYear', 'toDateString',
'toGMTString', 'toLocaleDateString', 'toLocaleTimeString',
'toLocaleString', 'toString', 'toTimeString', 'toUTCString',
'valueOf'
]
},
'Number': {
type: Number,
methods: [
'toExponential', 'toFixed', 'toLocaleString', 'toPrecision', 'toString',
'valueOf'
]
},
'String': {
type: String,
methods: [
'anchor', 'big', 'blink', 'bold', 'charAt', 'charCodeAt', 'concat',
'fixed', 'fontcolor', 'fontsize', 'indexOf', 'italics',
'lastIndexOf', 'link', 'match', 'replace', 'search', 'slice', 'small',
'split', 'strike', 'sub', 'substr', 'substring', 'sup', 'toLowerCase',
'toUpperCase', 'valueOf'
]
},
'RegExp': {
type: RegExp,
methods: [
'compile', 'exec', 'test'
]
}
};
/**
* Verifiers
* @namespace
*/
JsMockito.Verifiers = {
_export: ['never', 'zeroInteractions', 'noMoreInteractions', 'times', 'once'],
/**
* Test that a invocation never occurred. For example:
* <pre>
* verify(mock, never()).method();
* </pre>
* @see JsMockito.Verifiers.times(0)
*/
never: function() {
return new JsMockito.Verifiers.Times(0);
},
/** Test that no interaction were made on the mock. For example:
* <pre>
* verify(mock, zeroInteractions());
* </pre>
* @see JsMockito.verifyZeroInteractions()
*/
zeroInteractions: function() {
return new JsMockito.Verifiers.ZeroInteractions();
},
/** Test that no further interactions remain unverified on the mock. For
* example:
* <pre>
* verify(mock, noMoreInteractions());
* </pre>
* @see JsMockito.verifyNoMoreInteractions()
*/
noMoreInteractions: function() {
return new JsMockito.Verifiers.NoMoreInteractions();
},
/**
* Test that an invocation occurred a specific number of times. For example:
* <pre>
* verify(mock, times(2)).method();
* </pre>
*
* @param wanted The number of desired invocations
*/
times: function(wanted) {
return new JsMockito.Verifiers.Times(wanted);
},
/**
* Test that an invocation occurred exactly once. For example:
* <pre>
* verify(mock, once()).method();
* </pre>
* This is the default verifier.
* @see JsMockito.Verifiers.times(1)
*/
once: function() {
return new JsMockito.Verifiers.Times(1);
}
};
JsMockito.Verifier = function() { this.init.apply(this, arguments) };
JsMockito.Verifier.prototype = {
init: function() { },
verify: function(mock) {
var self = this;
return mock._jsMockitoVerifier(function() {
self.verifyInteractions.apply(self, arguments);
});
},
verifyInteractions: function(funcName, interactions, matchers, describeContext) {
},
updateVerifiedInteractions: function(interactions) {
JsMockito.each(interactions, function(interaction) {
interaction.verified = true;
});
},
buildDescription: function(message, funcName, matchers, describeContext) {
var description = new JsHamcrest.Description();
description.append(message + ': ' + funcName + '(');
JsMockito.each(matchers.slice(1), function(matcher, i) {
if (i > 0)
description.append(', ');
description.append('<');
matcher.describeTo(description);
description.append('>');
});
description.append(")");
if (describeContext) {
description.append(", 'this' being ");
matchers[0].describeTo(description);
}
return description;
}
};
JsMockito.verifier('Times', {
init: function(wanted) {
this.wanted = wanted;
},
verifyInteractions: function(funcName, allInteractions, matchers, describeContext) {
var interactions = JsMockito.grep(allInteractions, function(interaction) {
return JsMockito.matchArray(matchers, interaction.args);
});
if (interactions.length == this.wanted) {
this.updateVerifiedInteractions(interactions);
return;
}
var message;
if (interactions.length == 0) {
message = 'Wanted but not invoked';
} else if (this.wanted == 0) {
message = 'Never wanted but invoked';
} else if (this.wanted == 1) {
message = 'Wanted 1 invocation but got ' + interactions.length;
} else {
message = 'Wanted ' + this.wanted + ' invocations but got ' + interactions.length;
}
var description = this.buildDescription(message, funcName, matchers, describeContext);
throw description.get();
}
});
JsMockito.verifier('ZeroInteractions', {
verify: function(mock) {
var neverVerifier = JsMockito.Verifiers.never();
JsMockito.each(mock._jsMockitoMockFunctions(), function(mockFunc) {
neverVerifier.verify(mockFunc)();
});
}
});
JsMockito.verifier('NoMoreInteractions', {
verify: function(mock) {
var self = this;
JsMockito.each(mock._jsMockitoMockFunctions(), function(mockFunc) {
JsMockito.Verifier.prototype.verify.call(self, mockFunc)();
});
},
verifyInteractions: function(funcName, allInteractions, matchers, describeContext) {
var interactions = JsMockito.grep(allInteractions, function(interaction) {
return interaction.verified != true;
});
if (interactions.length == 0)
return;
var description = this.buildDescription(
"No interactions wanted, but " + interactions.length + " remains",
funcName, matchers, describeContext);
throw description.get();
}
});
/**
* Verifiers
* @namespace
*/
JsMockito.Integration = {
/**
* Import the public JsMockito API into the specified object (namespace)
*
* @param {object} target An object (namespace) that will be populated with
* the functions from the public JsMockito API
*/
importTo: function(target) {
for (var i = JsMockito._export.length; i > 0; --i) {
var exported = JsMockito._export[i-1];
target[exported] = JsMockito[exported];
}
for (var i = JsMockito.Verifiers._export.length; i > 0; --i) {
var exported = JsMockito.Verifiers._export[i-1];
target[exported] = JsMockito.Verifiers[exported];
}
},
/**
* Make the public JsMockito API available in Screw.Unit
* @see JsMockito.Integration.importTo(Screw.Matchers)
*/
screwunit: function() {
JsMockito.Integration.importTo(Screw.Matchers);
},
/**
* Make the public JsMockito API available to JsTestDriver
* @see JsMockito.Integration.importTo(window)
*/
JsTestDriver: function() {
JsMockito.Integration.importTo(window);
},
/**
* Make the public JsMockito API available to JsUnitTest
* @see JsMockito.Integration.importTo(JsUnitTest.Unit.Testcase.prototype)
*/
JsUnitTest: function() {
JsMockito.Integration.importTo(JsUnitTest.Unit.Testcase.prototype);
},
/**
* Make the public JsMockito API available to YUITest
* @see JsMockito.Integration.importTo(window)
*/
YUITest: function() {
JsMockito.Integration.importTo(window);
},
/**
* Make the public JsMockito API available to QUnit
* @see JsMockito.Integration.importTo(window)
*/
QUnit: function() {
JsMockito.Integration.importTo(window);
},
/**
* Make the public JsMockito API available to jsUnity
* @see JsMockito.Integration.importTo(jsUnity.env.defaultScope)
*/
jsUnity: function() {
JsMockito.Integration.importTo(jsUnity.env.defaultScope);
},
/**
* Make the public JsMockito API available to jSpec
* @see JsMockito.Integration.importTo(jSpec.defaultContext)
*/
jSpec: function() {
JsMockito.Integration.importTo(jSpec.defaultContext);
}
};