/
jasmine-fake-ajax.js
248 lines (222 loc) · 9.27 KB
/
jasmine-fake-ajax.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
(function($, jasmine) {
// Public interface.
jasmine.FakeAjax = {
realAjax: $.ajax,
clearContext: clearContext,
initContext: initContext,
loadTestData: loadTestData,
latestAjax: latestAjax,
latestAjaxWithUrlMatching: latestAjaxWithUrlMatching,
log: new Logger()
}
$.ajax = function(realOptions) {
jasmine.FakeAjax.recordedSession.addRealOptions(realOptions)
var allBypassableOptions = jasmine.FakeAjax.recordedSession.allBypassableOptions
var allFakeOptions = jasmine.FakeAjax.recordedSession.allFakeOptions
if (!_.isEmpty(findMatchingOptions(realOptions, allBypassableOptions))) {
return jasmine.FakeAjax.realAjax(realOptions)
} else if (!_.isEmpty(allFakeOptions)) {
var fakeOptions = findMatchingOptions(realOptions, allFakeOptions)
if (_.isEmpty(fakeOptions)) {
jasmine.FakeAjax.log.warn(messageWithContextInfo("No matching fake ajax registration found.", realOptions))
} else {
callAvailableCallbackHandlers(realOptions, fakeOptions)
}
} else {
jasmine.FakeAjax.log.warn(messageWithContextInfo("No fake ajax registrations found. Perhaps you forgot to register some using .fakeAjax?", realOptions))
}
}
function RecordedSession() {
// All registered fake ajax options.
this.allFakeOptions = []
// All registered ajax options that should be bypassed and delegated to real ajax.
this.allBypassableOptions = []
// All real ajax calls triggered by sut.
this.allRealOptions = []
this.registerFakeAjax = function(options) {
this.allFakeOptions.push(options)
}
this.addBypassableOptions = function(options) {
this.allBypassableOptions.push(options)
}
this.addRealOptions = function(options) {
this.allRealOptions.push(options)
}
}
function Logger() {
this.error = function(message) {
withFirebugConsole(function(c) {
c.error(message)
})
}
this.warn = function(message) {
withFirebugConsole(function(c) {
c.warn(message)
})
}
function withFirebugConsole(callback) {
if (window.console) {
callback(window.console)
}
}
}
function clearContext() {
jasmine.FakeAjax.recordedSession = new RecordedSession()
}
function initContext(options) {
_.each(options.registrations, function(options) {
jasmine.FakeAjax.recordedSession.registerFakeAjax(options)
})
}
function loadTestData(selector, url) {
var fixture
jasmine.FakeAjax.realAjax({
url: url,
type: 'get',
dataType: 'html',
async: false,
success: function(data) {
fixture = data
},
error: function() {
logAndThrow("Failed loading test data by url '" + url + "'.")
}
})
var testDataContainer = $(fixture).find(selector)
if (testDataContainer.length > 0) {
return testDataContainer.html()
} else {
logAndThrow("Failed loading test data by selector '" + selector + "' from url '" + url + "'.")
}
}
function latestAjax() {
var allRealOptions = jasmine.FakeAjax.recordedSession.allRealOptions
if (_.isEmpty(allRealOptions)) {
logAndThrow("Ajax hasn't yet been called in spec '" + jasmine.getEnv().currentSpec.description + "'.")
} else {
return lastWithUrlDecoded(allRealOptions)
}
}
function latestAjaxWithUrlMatching(partialUrl) {
var matchingAjaxCalls = _.filter(jasmine.FakeAjax.recordedSession.allRealOptions, function(ajaxOptions) {
return ajaxOptions.url.match(partialUrl)
})
if (_.isEmpty(matchingAjaxCalls)) {
logAndThrow("Matching url was not found by partial url '" + partialUrl + "' in spec '" +
jasmine.getEnv().currentSpec.description + "'.")
} else {
return lastWithUrlDecoded(matchingAjaxCalls)
}
}
function lastWithUrlDecoded(ajaxOptions) {
var last = _.last(ajaxOptions)
last.url = $.URLDecode(last.url)
return last
}
function logAndThrow(errorMessage) {
jasmine.FakeAjax.log.error(errorMessage)
throw errorMessage
}
function findMatchingOptions(realOptions, allOtherOptions) {
var comparableFields = ['url', 'type', 'data', 'dataType', 'async']
var allMatchingOptions = _.select(allOtherOptions, function(otherOptions) {
var real = _.clone(realOptions)
var other = _.clone(otherOptions)
_.each([real, other], function(o) {
o.type = (o.type || 'get').toLowerCase()
})
return _.all(comparableFields, function(field) {
return _.isUndefined(other[field]) ? true : _.isEqual(other[field], real[field])
})
})
if (allMatchingOptions.length > 1) {
logAndThrow("Multiple matching ajax options found, not able to decide which callbacks to use " +
"because the result was ambiguous. Real ajax options: " + JSON.stringify(realOptions) + ". " +
"All matching (and thus conflicting) options: " +
_.map(allMatchingOptions, function(options){ return JSON.stringify(options) }))
}
return _.first(allMatchingOptions)
}
function callAvailableCallbackHandlers(real, fake) {
function checkPreCondition() {
var possibleCallbackRules = ['success', 'successData', 'error', 'errorMessage']
var registeredCallbackRules = _.reduce(possibleCallbackRules, function(all, current) {
if (fake[current]) {
all.push(current)
}
return all
}, [])
if (registeredCallbackRules.length === 0) {
logAndThrow("Exactly one callback rule of [" + possibleCallbackRules.join(', ') + "] " +
"must be defined for url '" + real.url + "'. There was none.")
} else if (registeredCallbackRules.length > 1) {
logAndThrow("Exactly one callback rule of [" + possibleCallbackRules.join(', ') + "] " +
"must be defined for url '" + real.url + "'. There was " + registeredCallbackRules.length +
": [" + registeredCallbackRules.join(', ') + "].")
} else if ((fake.success || fake.successData) && !real.success) {
logAndThrow("Ajax success handler is not defined in system under test for url '" + real.url + "'.")
} else if ((fake.error || fake.errorMessage) && !real.error) {
logAndThrow("Ajax error handler is not defined in system under test for url '" + real.url + "'.")
} else {
return true
}
}
function callAvailableHandlers() {
function handleFunctionOrArrayCallbacks(property, callback) {
if (_.isFunction(real[property])) {
if (!_.isObject(fake[property]) || _.isArray(fake[property])) {
logAndThrow("Fake " + property + " must be an (" + property + " arguments) object when real " +
property + " is a function for url '" + real.url + "'.")
}
callback(real[property], fake[property])
} else if (_.isArray(real[property])) {
if (!_.isArray(fake[property])) {
logAndThrow("Real " + property + " is an array but fake " + property + " is not for url '" + real.url + "'.")
}
if (!_.isEqual(fake[property].length, real[property].length)) {
logAndThrow("Fake " + property + " has " + fake[property].length + " items but real " +
property + " has " + real[property].length + " items for url '" + real.url + "'.")
}
_.each(_.zip(real[property], fake[property]), function(realAndFake) {
callback(realAndFake[0], realAndFake[1])
})
} else {
logAndThrow("Real " + property + " must be a function or an array of functions for url '" + real.url + "'.")
}
}
if (real.beforeSend) {
real.beforeSend()
}
if (fake.success) {
handleFunctionOrArrayCallbacks('success', function(realSuccessCallback, fakeSuccess) {
realSuccessCallback.call(real.context, fakeSuccess.data, fakeSuccess.status, fakeSuccess.xhr)
})
} else if (fake.successData) {
real.success.call(real.context, fake.successData)
} else if (fake.error) {
handleFunctionOrArrayCallbacks('error', function(realErrorCallback, fakeError) {
realErrorCallback.call(real.context, fakeError.xhr, fakeError.status, fakeError.error)
})
} else if (fake.errorMessage) {
real.error.call(real.context, {responseText: fake.errorMessage})
}
if (real.complete) {
real.complete.call(real.context)
}
}
checkPreCondition()
callAvailableHandlers()
}
function messageWithContextInfo(message, realOptions) {
return message + " (spec: '" + jasmine.getEnv().currentSpec.description + "', actual ajax url that was called by application: '" + realOptions.url + "')"
}
})(jQuery, jasmine)
// Some global convenience functions.
function realAjax(options) { jasmine.FakeAjax.realAjax(options) }
function fakeAjax(options) { jasmine.FakeAjax.initContext(options) }
function registerFakeAjax(options) { jasmine.FakeAjax.recordedSession.registerFakeAjax(options) }
function useRealAjaxFor(options) { jasmine.FakeAjax.recordedSession.addBypassableOptions(options) }
function loadTestData(selector, url) { return jasmine.FakeAjax.loadTestData(selector, url) }
function latestAjax() { return jasmine.FakeAjax.latestAjax() }
function latestAjaxWithUrlMatching(partialUrl) { return jasmine.FakeAjax.latestAjaxWithUrlMatching(partialUrl) }
beforeEach(jasmine.FakeAjax.clearContext)