/
fake-ajax-spec.js
790 lines (699 loc) · 23.7 KB
/
fake-ajax-spec.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
describe('simple example', function() {
it('just works', function() {
var message = 'Hello '
registerFakeAjax({url: '/simple', successData: 'World!'})
$.get('/simple', function(data) {
message += data
})
expect(message).toEqual('Hello World!')
})
})
describe('rules for resolving which fake ajax options match the real options', function() {
it('default type is get', function() {
registerFakeAjax({url: '/a', successData: 1})
$.get('/a', successHandler)
expect(result.success.data).toEqual(1)
})
it('type is case-insensitive', function() {
fakeAjax({registrations:[
{url: '/a', type: 'gEt', successData: 1},
{url: '/b', type: 'PuT', successData: 2}
]})
$.ajax({url: '/a', type: 'GET', success: successHandler})
expect(result.success.data).toEqual(1)
$.ajax({url: '/b', type: 'PUT', success: successHandler})
expect(result.success.data).toEqual(2)
})
it('selects fake options with all given fields matching equivalent fields in real options', function() {
fakeAjax({registrations:[
{url: '/a', data: {user: 'cat'}, successData: 1},
{url: '/a', data: {user: 'dog'}, successData: 2},
{url: '/a', type: 'post', successData: 3},
{url: '/b', type: 'put', data: {user: 'bob', age: 30}, async: false, dataType: 'json', successData: 4},
{url: '/b', type: 'put', data: {user: 'bob', age: 30}, async: false, dataType: 'xml', successData: 5},
{url: '/c', successData: 6}
]})
$.ajax({url: '/a', type: 'get', data: {user: 'dog'}, success: successHandler})
expect(result.success.data).toEqual(2)
$.post('/a', successHandler)
expect(result.success.data).toEqual(3)
$.ajax({url: '/b', type: 'put', dataType: 'json', async: false, data: {user: 'bob', age: 30}, success: successHandler})
expect(result.success.data).toEqual(4)
$.ajax({url: '/c', data: {age: 99}, async: true, success: successHandler})
expect(result.success.data).toEqual(6)
})
it('compares url', function() {
fakeAjax({registrations:[
{url: '/a', successData: 1},
{url: '/b', successData: 2}
]})
$.get('/b', successHandler)
expect(result.success.data).toEqual(2)
})
it('compares type', function() {
fakeAjax({registrations:[
{type: 'put', successData: 1},
{type: 'delete', successData: 2}
]})
$.ajax({type: 'delete', success: successHandler})
expect(result.success.data).toEqual(2)
})
it('compares data', function() {
fakeAjax({registrations:[
{data: {user: 'dog'}, successData: 1},
{data: {user: 'cat'}, successData: 2}
]})
$.ajax({data: {user: 'cat'}, success: successHandler})
expect(result.success.data).toEqual(2)
})
it('compares dataType', function() {
fakeAjax({registrations:[
{dataType: 'json', successData: 1},
{dataType: 'xml', successData: 2}
]})
$.ajax({dataType: 'json', success: successHandler})
expect(result.success.data).toEqual(1)
})
it('compares async', function() {
fakeAjax({registrations:[
{async: true, successData: 1},
{async: false, successData: 2}
]})
$.ajax({async: true, success: successHandler})
expect(result.success.data).toEqual(1)
})
})
describe('registering fake ajax options', function() {
beforeEach(function() {
registerFakeAjax({url: 'e', successData: 5})
})
it('allows adding options groupped and/or one by one', function() {
registerFakeAjax({url: 'd', successData: 4})
fakeAjax({registrations:[
{url: 'b', successData: 2},
{url: 'c', successData: 3}
]})
registerFakeAjax({url: 'a', successData: 1})
function assertResult(url, expectedResult) {
$.ajax({url: url, success: successHandler})
expect(result.success.data).toEqual(expectedResult)
}
_.each([['a', 1], ['b', 2], ['c', 3], ['d', 4], ['e', 5]], function(entry) {
assertResult(entry[0], entry[1])
})
})
})
describe('using real ajax for some ajax calls', function() {
var expectedData
var realOptions = {
url: 'example-fixture.html',
async: false,
dataType: 'html',
success: function(data) {
expectedData = data
}
}
beforeEach(function() {
expectedData = 'initial'
})
it('delegates registered ajax options (that should be bypassed) to real ajax', function() {
useRealAjaxFor({url: 'example-fixture.html'})
$.ajax(realOptions)
expect($(expectedData)).toHaveText('example')
})
it('delegates to real ajax only if options match', function() {
var exampleOptions = {url: 'example-fixture.html'}
_.each([{async: true}, {async: false, dataType: 'xml'}], function(nonMatchingFields) {
useRealAjaxFor($.extend(exampleOptions, nonMatchingFields))
$.ajax(realOptions)
expect(expectedData).toEqual('initial')
})
})
})
describe('loading test data', function() {
describe('json', function() {
it('json object from external file', function() {
registerFakeAjax({url: 'a', successData: TestResponses.jsonObject})
$.getJSON('a',successHandler)
expect(result.success.data.name).toEqual('John')
expect(result.success.data.age).toEqual(30)
expect(result.success.data.children).toEqual([{name: 'Mary', age: 2}, {name: 'Jill', age: 4}])
})
it('json string from external file', function() {
registerFakeAjax({url: 'b', successData: $.parseJSON(TestResponses.jsonString)})
$.getJSON('b',successHandler)
expect(result.success.data.name).toEqual('Tim')
expect(result.success.data.age).toEqual('10')
expect(result.success.data.toys).toEqual(['car1', 'car2'])
})
})
})
// Fake AJAX with DOM, single AJAX call. Response test data is loaded using .loadTestData.
describe('showing questions', function() {
beforeEach(function() {
setFixtures('<button class="showQuestions"/><div class="questions"></div>')
sut.setupQuestionsBehavior()
})
describe('succeeds', function() {
beforeEach(function() {
fakeAjax({registrations:[{url: '/questions/list', successData: loadTestData('.questions', 'fake-ajax-fixture.html')}]})
$('.showQuestions').click()
})
it('shows the list of questions fetched from server', function() {
expect($('.question').length).toEqual(3)
expect($('.question').last()).toHaveText('Question 3')
})
})
describe('fails', function() {
beforeEach(function() {
fakeAjax({registrations:[{url: '/questions/list', errorMessage: 'Failed loading questions.'}]})
$('.showQuestions').click()
})
it('shows error message from server', function() {
expect($('.questions')).toHaveText('Failed loading questions.')
})
})
})
// Fake AJAX without DOM.
describe('.countResponseLength', function() {
describe('succeeds', function() {
beforeEach(function() {
fakeAjax({registrations:[{url: '/succeeds', successData: 'Jasmine FTW!'}]})
})
it('counts response length', function() {
expect(sut.countResponseLength({url: '/succeeds'})).toEqual(12)
})
})
describe('fails', function() {
beforeEach(function() {
fakeAjax({registrations:[{url: '/fails', errorMessage: 'argh'}]})
})
it('yields given default value', function() {
expect(sut.countResponseLength({url: '/fails', defaultOnError: 666})).toEqual(666)
})
it('executes given error handler', function() {
var errorMessage
function errorHandler(xhr) {
errorMessage = xhr.responseText
}
sut.countResponseLength({url: '/fails', errorHandler: errorHandler})
expect(errorMessage).toEqual('argh')
})
})
})
// Multiple related AJAX calls, some succeed, some fail.
describe('clicking question', function() {
describe('author is not available', function() {
beforeEach(function() {
setFixtures('<ul class="questions"><li id="question1">q1</li><li id="question2">q2</li></ul>' +
'<div class="answerContainer"></div>')
sut.setupAnswersBehavior()
fakeAjax({registrations:[
{url: '/answers/get?questionId=question2', successData: loadTestData('.answer2', 'fake-ajax-fixture.html')},
{url: '/authors/get?answerId=answer2', errorMessage: 'author data not available'},
{url: '/onError', successData: 'Please try again later.'}
]})
$('.questions li').last().click()
})
it('shows answer', function() {
expect($('.answer')).toHaveText('Answer 2')
})
it('shows error message instead of author details', function() {
expect($('.author')).toHaveText('Please try again later.')
})
})
})
describe('when checking what is sent to the server', function() {
beforeEach(function() {
sut.setupMultipleAjaxCalls()
})
it('sends expected data', function() {
expect(latestAjaxWithUrlMatching('first').data).toEqual({'param1': 'value1', 'param2': 'value2'})
expect(latestAjax().url).toEqual('/third')
})
it('decodes url to enhance readability of values', function() {
expect(latestAjaxWithUrlMatching('second').url).toContain('+<foo>+"bar+&?#')
})
})
// When response is expected to be in JSON format ($.getJSON is called in SUT).
describe('showing user info', function() {
beforeEach(function() {
setFixtures('<button class="showUser"/><div class="user"><div class="name"></div><div class="age"></div></div>')
sut.setupUserBehavior()
fakeAjax({registrations:[{url: '/user', successData: {name: 'John', age: 30}}]})
$('.showUser').click()
})
it('shows name', function() {
expect($('.user .name')).toHaveText('John')
})
it('shows age', function() {
expect($('.user .age')).toHaveText('30')
})
})
describe('after each spec', function() {
it('context is cleared', function() {
expect(jasmine.FakeAjax.urls).toBeFalsy()
})
})
describe('supported callbacks', function() {
var beforeSendWasCalled = false
var successWasCalled = false
var completeWasCalled = false
beforeEach(function() {
fakeAjax({registrations:[{url: '/example', successData: 'yay'}]})
$.ajax({
url: '/example',
beforeSend: function() {
beforeSendWasCalled = true
},
success: function() {
successWasCalled = true
},
complete: function() {
completeWasCalled = true
}
})
})
it('.beforeSend', function() {
expect(beforeSendWasCalled).toBeTruthy()
})
it('.success', function() {
expect(successWasCalled).toBeTruthy()
})
it('.complete', function() {
expect(completeWasCalled).toBeTruthy()
})
describe('success', function() {
it('passes given data, status and xhr to sut', function() {
registerFakeAjax({
url: 'a',
success: {
data: {name: 'Bob'},
status: 'ok',
xhr: {
status: 200,
responseText: 'yay'
}
}
})
$.ajax({
url: 'a',
success: function(data, status, xhr) {
result.data = data
result.status = status
result.xhr = xhr
}
})
expect(result.data.name).toEqual('Bob')
expect(result.status).toEqual('ok')
expect(result.xhr.status).toEqual(200)
expect(result.xhr.responseText).toEqual('yay')
})
it('allows using successData convenience property for cases it is enough', function() {
registerFakeAjax({
url: 'a',
successData: 'it worked'
})
$.ajax({
url: 'a',
success: function(data) {
result.data = data
}
})
expect(result.data).toEqual('it worked')
})
})
describe('error', function() {
it('passes given xhr, status and error to callback', function() {
registerFakeAjax({
url: 'a',
error: {
xhr: {
status: 500,
statusText: 'Internal Server Error',
responseText: 'oh noez'
},
status: 'fail',
error: 'bad'
}
})
$.ajax({
url: 'a',
error: function(xhr, status, error) {
result.xhr = xhr
result.status = status
result.error = error
}
})
expect(result.xhr.status).toEqual(500)
expect(result.xhr.statusText).toEqual('Internal Server Error')
expect(result.xhr.responseText).toEqual('oh noez')
expect(result.status).toEqual('fail')
expect(result.error).toEqual('bad')
})
it('allows using errorMessage convenience property for cases it is enough', function() {
registerFakeAjax({
url: 'a',
errorMessage: 'fail'
})
$.ajax({
url: 'a',
error: function(xhr) {
result.errorMessage = xhr.responseText
}
})
expect(result.errorMessage).toEqual('fail')
})
})
describe('array of callbacks', function() {
it('success', function() {
result.success.data = ""
registerFakeAjax({
url: 'a',
success: _.map([1, 2, 3], function(x){ return {data: x} })
})
$.ajax({
url: 'a',
success: _.map(['a', 'b', 'c'], function(x){ return function(data){ result.success.data += x + data } })
})
expect(result.success.data).toEqual('a1b2c3')
})
it('error', function() {
var result = ""
registerFakeAjax({
url: 'a',
error: [
{xhr: {status: 404, responseText: '1'}},
{xhr: {responseText: '2'}},
{xhr: {responseText: '3', statusText: 'argh'}} ]
})
$.ajax({
url: 'a',
error: [
function(xhr) { result += ('a' + xhr.responseText + xhr.status) },
function(xhr) { result += ('b' + xhr.responseText) },
function(xhr) { result += ('c' + xhr.responseText + xhr.statusText) }
]
})
expect(result).toEqual('a1404b2c3argh')
})
})
})
describe('context option', function() {
var Context
beforeEach(function() {
Context = {
onSuccess: function(data) {},
onError: function(xhr) {},
onComplete: function() {}
}
spyOn(Context, 'onSuccess')
spyOn(Context, 'onError')
spyOn(Context, 'onComplete')
fakeAjax({registrations:[
{url: '/test/context/success', successData: 'success data'},
{url: '/test/context/error', errorMessage: 'error message'},
{url: '/test/context/complete', successData: 'any'}
]})
})
function callAjaxWithContext(url) {
$.ajax({
context: Context,
url: url,
success: function(data) {
expect(this).toBe(Context)
this.onSuccess(data)
},
error: function(xhr) {
expect(this).toBe(Context)
this.onError(xhr)
},
complete: function() {
expect(this).toBe(Context)
this.onComplete()
}
})
}
it('is supported for success callback', function() {
callAjaxWithContext('/test/context/success')
expect(Context.onSuccess).toHaveBeenCalledWith('success data')
})
it('is supported for error callback', function() {
callAjaxWithContext('/test/context/error')
expect(Context.onError).toHaveBeenCalledWith({responseText: 'error message'})
})
it('is supported for complete callback', function() {
callAjaxWithContext('/test/context/complete')
expect(Context.onComplete).toHaveBeenCalled()
})
})
describe('using real jQuery.ajax', function() {
it('supports global .realAjax convenience handle', function() {
realAjax({
url: 'example-fixture.html',
async: false,
dataType: 'html',
success: successHandler
})
expect($(result.success.data)).toHaveText('example')
})
})
describe('logging', function() {
var testLog
function TestLog() {
this.warnings = []
this.errors = []
this.latestWarning = function() { return _.last(this.warnings) }
jasmine.FakeAjax.log.warn = function(message) {
testLog.warnings.push(message)
}
jasmine.FakeAjax.log.error = function(message) {
testLog.errors.push(message)
}
}
var customMatchers = {
toLogAndThrow: function(expectedMessage) {
var result = false
var exception
try {
this.actual()
} catch (message) {
exception = message
}
if (exception) {
result = (this.env.equals_(exception, expectedMessage) && this.env.contains_(testLog.errors, expectedMessage))
}
this.message = function() {
return "Expected function to log and throw '" + expectedMessage + "'. Logged error messages: [" +
testLog.errors + "]. Actual error message thrown by the function was '" + exception + "'."
}
return result
}
}
beforeEach(function() {
this.addMatchers(customMatchers)
testLog = new TestLog()
})
describe('without fake ajax options', function() {
it('logs warning', function() {
$.get('/example')
expect(testLog.latestWarning()).toEqual("No fake ajax registrations found. Perhaps you forgot to register some using .fakeAjax? (spec: " +
"'logs warning', actual ajax url that was called by application: '/example')")
})
})
describe('without matching url', function() {
it('logs warning with real url and spec description', function() {
fakeAjax({registrations:[{url: '/this'}]})
$.get('/that', function(){})
expect(testLog.latestWarning()).toEqual("No matching fake ajax registration found. (spec: " +
"'logs warning with real url and spec description', actual ajax url that was called by application: '/that')")
})
})
describe('when multiple matching fake options are found', function() {
it('logs and throws error message', function() {
fakeAjax({registrations:[
{url: 'a'},
{url: 'a', type: 'get'}
]})
expect(function() {
$.get('a')
}).toLogAndThrow('Multiple matching ajax options found, not able to decide which callbacks to use ' +
'because the result was ambiguous. Real ajax options: {"type":"get","url":"a"}. ' +
'All matching (and thus conflicting) options: {"url":"a"},{"url":"a","type":"get"}')
})
})
describe('without success handler in real options (though successData is defined in fake options)', function() {
it('logs and throws error message', function() {
fakeAjax({registrations:[{url: 'a', successData: 1}]})
expect(function() {
$.get('a')
}).toLogAndThrow("Ajax success handler is not defined in system under test for url 'a'.")
})
})
describe('without error handler in real options (though errorMessage is defined in fake options)', function() {
it('logs and throws error message', function() {
fakeAjax({registrations:[{url: 'a', errorMessage: 1}]})
expect(function() {
$.get('a')
}).toLogAndThrow("Ajax error handler is not defined in system under test for url 'a'.")
})
})
describe('when no callback instruction is specified', function() {
it('logs and throws error message', function() {
fakeAjax({registrations:[{url: 'a'}]})
expect(function() {
$.get('a')
}).toLogAndThrow("Exactly one callback rule of [success, successData, error, errorMessage] " +
"must be defined for url 'a'. There was none.")
})
})
describe('when fake success is an array but real success is not', function() {
it('logs and throws error message', function() {
registerFakeAjax({
url: 'a',
success: []
})
expect(function() {
$.ajax({
url: 'a',
success: function(){}
})
}).toLogAndThrow("Fake success must be an (success arguments) object when real success is a function for url 'a'.")
})
})
describe('when real success has different number of items than fake success', function() {
it('logs and throws error message', function() {
registerFakeAjax({
url: 'a',
success: [1]
})
expect(function() {
$.ajax({
url: 'a',
success: [1, 2]
})
}).toLogAndThrow("Fake success has 1 items but real success has 2 items for url 'a'.")
})
})
describe('when fake success is given but real success is not a function or an array', function() {
it('logs and throws error message', function() {
registerFakeAjax({
url: 'a',
success: {}
})
expect(function() {
$.ajax({
url: 'a',
success: "foo"
})
}).toLogAndThrow("Real success must be a function or an array of functions for url 'a'.")
})
})
describe('when fake error is an array but real error is not', function() {
it('logs and throws error message', function() {
registerFakeAjax({
url: 'a',
error: []
})
expect(function() {
$.ajax({
url: 'a',
error: function(){}
})
}).toLogAndThrow("Fake error must be an (error arguments) object when real error is a function for url 'a'.")
})
})
describe('when real error is an array but fake error is not', function() {
it('logs and throws error message', function() {
registerFakeAjax({
url: 'a',
error: {}
})
expect(function() {
$.ajax({
url: 'a',
error: []
})
}).toLogAndThrow("Real error is an array but fake error is not for url 'a'.")
})
})
describe('when real error has different number of items than fake error', function() {
it('logs and throws error message', function() {
registerFakeAjax({
url: 'a',
error: [1]
})
expect(function() {
$.ajax({
url: 'a',
error: [1, 2]
})
}).toLogAndThrow("Fake error has 1 items but real error has 2 items for url 'a'.")
})
})
describe('when fake error is given but real error is not a function or an array', function() {
it('logs and throws error message', function() {
registerFakeAjax({
url: 'a',
error: {}
})
expect(function() {
$.ajax({
url: 'a',
error: "foo"
})
}).toLogAndThrow("Real error must be a function or an array of functions for url 'a'.")
})
})
describe('when more than one callback rule is given', function() {
it('logs and throws error message', function() {
registerFakeAjax({url: 'a', error: {}, successData: 'any', success: {}})
expect(function() {
$.get('a', successHandler)
}).toLogAndThrow("Exactly one callback rule of [success, successData, error, errorMessage] " +
"must be defined for url 'a'. There was 3: [success, successData, error].")
})
})
describe('when fixture is not found', function() {
it('logs and throws error message', function() {
expect(function() {
loadTestData('.any', 'unknown-fixture.html')
}).toLogAndThrow("Failed loading test data by url 'unknown-fixture.html'.")
})
})
describe('when test data is not found from fixture', function() {
it('logs and throws error message', function() {
expect(function() {
loadTestData('.unknown', 'example-fixture.html')
}).toLogAndThrow("Failed loading test data by selector '.unknown' from url 'example-fixture.html'.")
})
})
describe('when latest ajax is not found', function() {
it('logs and throws error message with spec description', function() {
expect(function() {
latestAjax()
}).toLogAndThrow("Ajax hasn't yet been called in spec 'logs and throws error message with spec description'.")
})
})
describe('when matching url is not found', function() {
it('logs and throws error message with partial url and spec description', function() {
expect(function() {
latestAjaxWithUrlMatching('/not-found')
}).toLogAndThrow("Matching url was not found by partial url '/not-found' in spec " +
"'logs and throws error message with partial url and spec description'.")
})
})
})
// Test helpers
var result
function successHandler(data, status, xhr) {
result.success.data = data
result.success.status = status
result.success.xhr = xhr
}
beforeEach(function() {
result = {
success: {},
error: {}
}
})