This repository was archived by the owner on Apr 12, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 27.4k
/
Copy pathbrowserSpecs.js
executable file
·656 lines (498 loc) · 20.7 KB
/
browserSpecs.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
'use strict';
function MockWindow() {
var events = {};
var timeouts = this.timeouts = [];
this.setTimeout = function(fn) {
return timeouts.push(fn) - 1;
};
this.clearTimeout = function(id) {
timeouts[id] = noop;
};
this.setTimeout.flush = function() {
var length = timeouts.length;
while (length-- > 0) timeouts.shift()();
};
this.addEventListener = function(name, listener) {
if (angular.isUndefined(events[name])) events[name] = [];
events[name].push(listener);
};
this.attachEvent = function(name, listener) {
this.addEventListener(name.substr(2), listener);
};
this.removeEventListener = noop;
this.detachEvent = noop;
this.fire = function(name) {
forEach(events[name], function(fn) {
fn({type: name}); // type to make jQuery happy
});
};
this.location = {
href: 'http://server/',
replace: noop
};
this.history = {
replaceState: noop,
pushState: noop
};
}
function MockDocument() {
var self = this;
this[0] = window.document;
this.basePath = '/';
this.find = function(name) {
if (name == 'base') {
return {
attr: function(name){
if (name == 'href') {
return self.basePath;
} else {
throw new Error(name);
}
}
};
} else {
throw new Error(name);
}
};
}
describe('browser', function() {
/* global Browser: false */
var browser, fakeWindow, fakeDocument, logs, scripts, removedScripts, sniffer;
beforeEach(function() {
scripts = [];
removedScripts = [];
sniffer = {history: true, hashchange: true};
fakeWindow = new MockWindow();
fakeDocument = new MockDocument();
var fakeBody = [{appendChild: function(node){scripts.push(node);},
removeChild: function(node){removedScripts.push(node);}}];
logs = {log:[], warn:[], info:[], error:[]};
var fakeLog = {log: function() { logs.log.push(slice.call(arguments)); },
warn: function() { logs.warn.push(slice.call(arguments)); },
info: function() { logs.info.push(slice.call(arguments)); },
error: function() { logs.error.push(slice.call(arguments)); }};
browser = new Browser(fakeWindow, fakeDocument, fakeLog, sniffer);
});
it('should contain cookie cruncher', function() {
expect(browser.cookies).toBeDefined();
});
describe('outstading requests', function() {
it('should process callbacks immedietly with no outstanding requests', function() {
var callback = jasmine.createSpy('callback');
browser.notifyWhenNoOutstandingRequests(callback);
expect(callback).toHaveBeenCalled();
});
});
describe('defer', function() {
it('should execute fn asynchroniously via setTimeout', function() {
var callback = jasmine.createSpy('deferred');
browser.defer(callback);
expect(callback).not.toHaveBeenCalled();
fakeWindow.setTimeout.flush();
expect(callback).toHaveBeenCalledOnce();
});
it('should update outstandingRequests counter', function() {
var callback = jasmine.createSpy('deferred');
browser.defer(callback);
expect(callback).not.toHaveBeenCalled();
fakeWindow.setTimeout.flush();
expect(callback).toHaveBeenCalledOnce();
});
it('should return unique deferId', function() {
var deferId1 = browser.defer(noop),
deferId2 = browser.defer(noop);
expect(deferId1).toBeDefined();
expect(deferId2).toBeDefined();
expect(deferId1).not.toEqual(deferId2);
});
describe('cancel', function() {
it('should allow tasks to be canceled with returned deferId', function() {
var log = [],
deferId1 = browser.defer(function() { log.push('cancel me'); }),
deferId2 = browser.defer(function() { log.push('ok'); }),
deferId3 = browser.defer(function() { log.push('cancel me, now!'); });
expect(log).toEqual([]);
expect(browser.defer.cancel(deferId1)).toBe(true);
expect(browser.defer.cancel(deferId3)).toBe(true);
fakeWindow.setTimeout.flush();
expect(log).toEqual(['ok']);
expect(browser.defer.cancel(deferId2)).toBe(false);
});
});
});
describe('cookies', function() {
function deleteAllCookies() {
var cookies = document.cookie.split(";");
var path = location.pathname;
for (var i = 0; i < cookies.length; i++) {
var cookie = cookies[i];
var eqPos = cookie.indexOf("=");
var name = eqPos > -1 ? cookie.substr(0, eqPos) : cookie;
var parts = path.split('/');
while (parts.length) {
document.cookie = name + "=;path=" + (parts.join('/') || '/') + ";expires=Thu, 01 Jan 1970 00:00:00 GMT";
parts.pop();
}
}
}
beforeEach(function() {
deleteAllCookies();
expect(document.cookie).toEqual('');
});
afterEach(function() {
deleteAllCookies();
expect(document.cookie).toEqual('');
});
describe('remove all via (null)', function() {
it('should do nothing when no cookies are set', function() {
browser.cookies(null);
expect(document.cookie).toEqual('');
expect(browser.cookies()).toEqual({});
});
});
describe('remove via cookies(cookieName, undefined)', function() {
it('should remove a cookie when it is present', function() {
document.cookie = 'foo=bar;path=/';
browser.cookies('foo', undefined);
expect(document.cookie).toEqual('');
expect(browser.cookies()).toEqual({});
});
it('should do nothing when an nonexisting cookie is being removed', function() {
browser.cookies('doesntexist', undefined);
expect(document.cookie).toEqual('');
expect(browser.cookies()).toEqual({});
});
});
describe('put via cookies(cookieName, string)', function() {
it('should create and store a cookie', function() {
browser.cookies('cookieName', 'cookie=Value');
expect(document.cookie).toMatch(/cookieName=cookie%3DValue;? ?/);
expect(browser.cookies()).toEqual({'cookieName':'cookie=Value'});
});
it('should overwrite an existing unsynced cookie', function() {
document.cookie = "cookie=new;path=/";
var oldVal = browser.cookies('cookie', 'newer');
expect(document.cookie).toEqual('cookie=newer');
expect(browser.cookies()).toEqual({'cookie':'newer'});
expect(oldVal).not.toBeDefined();
});
it('should encode both name and value', function() {
browser.cookies('cookie1=', 'val;ue');
browser.cookies('cookie2=bar;baz', 'val=ue');
var rawCookies = document.cookie.split("; "); //order is not guaranteed, so we need to parse
expect(rawCookies.length).toEqual(2);
expect(rawCookies).toContain('cookie1%3D=val%3Bue');
expect(rawCookies).toContain('cookie2%3Dbar%3Bbaz=val%3Due');
});
it('should log warnings when 4kb per cookie storage limit is reached', function() {
var i, longVal = '', cookieStr;
for(i=0; i<4083; i++) {
longVal += 'x';
}
cookieStr = document.cookie;
browser.cookies('x', longVal); //total size 4093-4096, so it should go through
expect(document.cookie).not.toEqual(cookieStr);
expect(browser.cookies()['x']).toEqual(longVal);
expect(logs.warn).toEqual([]);
browser.cookies('x', longVal + 'xxxx'); //total size 4097-4099, a warning should be logged
expect(logs.warn).toEqual(
[[ "Cookie 'x' possibly not set or overflowed because it was too large (4097 > 4096 " +
"bytes)!" ]]);
//force browser to dropped a cookie and make sure that the cache is not out of sync
browser.cookies('x', 'shortVal');
expect(browser.cookies().x).toEqual('shortVal'); //needed to prime the cache
cookieStr = document.cookie;
browser.cookies('x', longVal + longVal + longVal); //should be too long for all browsers
if (document.cookie !== cookieStr) {
this.fail(new Error("browser didn't drop long cookie when it was expected. make the " +
"cookie in this test longer"));
}
expect(browser.cookies().x).toEqual('shortVal');
});
});
describe('put via cookies(cookieName, string), if no <base href> ', function () {
beforeEach(function () {
fakeDocument.basePath = undefined;
});
it('should default path in cookie to "" (empty string)', function () {
browser.cookies('cookie', 'bender');
// This only fails in Safari and IE when cookiePath returns undefined
// Where it now succeeds since baseHref return '' instead of undefined
expect(document.cookie).toEqual('cookie=bender');
});
});
describe('get via cookies()[cookieName]', function() {
it('should return undefined for nonexistent cookie', function() {
expect(browser.cookies().nonexistent).not.toBeDefined();
});
it ('should return a value for an existing cookie', function() {
document.cookie = "foo=bar=baz;path=/";
expect(browser.cookies().foo).toEqual('bar=baz');
});
it('should return the the first value provided for a cookie', function() {
// For a cookie that has different values that differ by path, the
// value for the most specific path appears first. browser.cookies()
// should provide that value for the cookie.
document.cookie = 'foo="first"; foo="second"';
expect(browser.cookies()['foo']).toBe('"first"');
});
it ('should decode cookie values that were encoded by puts', function() {
document.cookie = "cookie2%3Dbar%3Bbaz=val%3Due;path=/";
expect(browser.cookies()['cookie2=bar;baz']).toEqual('val=ue');
});
it('should preserve leading & trailing spaces in names and values', function() {
browser.cookies(' cookie name ', ' cookie value ');
expect(browser.cookies()[' cookie name ']).toEqual(' cookie value ');
expect(browser.cookies()['cookie name']).not.toBeDefined();
});
it('should decode special characters in cookie values', function() {
document.cookie = 'cookie_name=cookie_value_%E2%82%AC';
expect(browser.cookies()['cookie_name']).toEqual('cookie_value_€');
});
it('should not decode cookie values that do not appear to be encoded', function() {
document.cookie = 'cookie_name=cookie_value_%XX';
expect(browser.cookies()['cookie_name']).toEqual('cookie_value_%XX');
});
});
describe('getAll via cookies()', function() {
it('should return cookies as hash', function() {
document.cookie = "foo1=bar1;path=/";
document.cookie = "foo2=bar2;path=/";
expect(browser.cookies()).toEqual({'foo1':'bar1', 'foo2':'bar2'});
});
it('should return empty hash if no cookies exist', function() {
expect(browser.cookies()).toEqual({});
});
});
it('should pick up external changes made to browser cookies', function() {
browser.cookies('oatmealCookie', 'drool');
expect(browser.cookies()).toEqual({'oatmealCookie':'drool'});
document.cookie = 'oatmealCookie=changed;path=/';
expect(browser.cookies().oatmealCookie).toEqual('changed');
});
it('should initialize cookie cache with existing cookies', function() {
document.cookie = "existingCookie=existingValue;path=/";
expect(browser.cookies()).toEqual({'existingCookie':'existingValue'});
});
});
describe('poller', function() {
it('should call functions in pollFns in regular intervals', function() {
var log = '';
browser.addPollFn(function() {log+='a';});
browser.addPollFn(function() {log+='b';});
expect(log).toEqual('');
fakeWindow.setTimeout.flush();
expect(log).toEqual('ab');
fakeWindow.setTimeout.flush();
expect(log).toEqual('abab');
});
it('should startPoller', function() {
expect(fakeWindow.timeouts.length).toEqual(0);
browser.addPollFn(function() {});
expect(fakeWindow.timeouts.length).toEqual(1);
//should remain 1 as it is the check fn
browser.addPollFn(function() {});
expect(fakeWindow.timeouts.length).toEqual(1);
});
it('should return fn that was passed into addPollFn', function() {
var fn = function() { return 1; };
var returnedFn = browser.addPollFn(fn);
expect(returnedFn).toBe(fn);
});
});
describe('url', function() {
var pushState, replaceState, locationReplace;
beforeEach(function() {
pushState = spyOn(fakeWindow.history, 'pushState');
replaceState = spyOn(fakeWindow.history, 'replaceState');
locationReplace = spyOn(fakeWindow.location, 'replace');
});
it('should return current location.href', function() {
fakeWindow.location.href = 'http://test.com';
expect(browser.url()).toEqual('http://test.com');
fakeWindow.location.href = 'https://another.com';
expect(browser.url()).toEqual('https://another.com');
});
it('should use history.pushState when available', function() {
sniffer.history = true;
browser.url('http://new.org');
expect(pushState).toHaveBeenCalledOnce();
expect(pushState.argsForCall[0][2]).toEqual('http://new.org');
expect(replaceState).not.toHaveBeenCalled();
expect(locationReplace).not.toHaveBeenCalled();
expect(fakeWindow.location.href).toEqual('http://server/');
});
it('should use history.replaceState when available', function() {
sniffer.history = true;
browser.url('http://new.org', true);
expect(replaceState).toHaveBeenCalledOnce();
expect(replaceState.argsForCall[0][2]).toEqual('http://new.org');
expect(pushState).not.toHaveBeenCalled();
expect(locationReplace).not.toHaveBeenCalled();
expect(fakeWindow.location.href).toEqual('http://server/');
});
it('should set location.href when pushState not available', function() {
sniffer.history = false;
browser.url('http://new.org');
expect(fakeWindow.location.href).toEqual('http://new.org');
expect(pushState).not.toHaveBeenCalled();
expect(replaceState).not.toHaveBeenCalled();
expect(locationReplace).not.toHaveBeenCalled();
});
it('should use location.replace when history.replaceState not available', function() {
sniffer.history = false;
browser.url('http://new.org', true);
expect(locationReplace).toHaveBeenCalledWith('http://new.org');
expect(pushState).not.toHaveBeenCalled();
expect(replaceState).not.toHaveBeenCalled();
expect(fakeWindow.location.href).toEqual('http://server/');
});
it('should return $browser to allow chaining', function() {
expect(browser.url('http://any.com')).toBe(browser);
});
it('should decode single quotes to work around FF bug 407273', function() {
fakeWindow.location.href = "http://ff-bug/?single%27quote";
expect(browser.url()).toBe("http://ff-bug/?single'quote");
});
it('should not set URL when the URL is already set', function() {
var current = fakeWindow.location.href;
sniffer.history = false;
fakeWindow.location.href = 'dontchange';
browser.url(current);
expect(fakeWindow.location.href).toBe('dontchange');
});
});
describe('urlChange', function() {
var callback;
beforeEach(function() {
callback = jasmine.createSpy('onUrlChange');
});
afterEach(function() {
if (!jQuery) jqLiteDealoc(fakeWindow);
});
it('should return registered callback', function() {
expect(browser.onUrlChange(callback)).toBe(callback);
});
it('should forward popstate event with new url when history supported', function() {
sniffer.history = true;
browser.onUrlChange(callback);
fakeWindow.location.href = 'http://server/new';
fakeWindow.fire('popstate');
expect(callback).toHaveBeenCalledWith('http://server/new');
fakeWindow.fire('hashchange');
fakeWindow.setTimeout.flush();
expect(callback).toHaveBeenCalledOnce();
});
it('should forward only popstate event when both history and hashchange supported', function() {
sniffer.history = true;
sniffer.hashchange = true;
browser.onUrlChange(callback);
fakeWindow.location.href = 'http://server/new';
fakeWindow.fire('popstate');
expect(callback).toHaveBeenCalledWith('http://server/new');
fakeWindow.fire('hashchange');
fakeWindow.setTimeout.flush();
expect(callback).toHaveBeenCalledOnce();
});
it('should forward hashchange event with new url when only hashchange supported', function() {
sniffer.history = false;
sniffer.hashchange = true;
browser.onUrlChange(callback);
fakeWindow.location.href = 'http://server/new';
fakeWindow.fire('hashchange');
expect(callback).toHaveBeenCalledWith('http://server/new');
fakeWindow.fire('popstate');
fakeWindow.setTimeout.flush();
expect(callback).toHaveBeenCalledOnce();
});
it('should use polling when neither history nor hashchange supported', function() {
sniffer.history = false;
sniffer.hashchange = false;
browser.onUrlChange(callback);
fakeWindow.location.href = 'http://server.new';
fakeWindow.setTimeout.flush();
expect(callback).toHaveBeenCalledWith('http://server.new');
callback.reset();
fakeWindow.fire('popstate');
fakeWindow.fire('hashchange');
expect(callback).not.toHaveBeenCalled();
});
describe('after an initial location change by browser.url method when neither history nor hashchange supported', function() {
beforeEach(function() {
sniffer.history = false;
sniffer.hashchange = false;
browser.url("http://server.current");
});
it('should fire callback with the correct URL on location change outside of angular', function() {
browser.onUrlChange(callback);
fakeWindow.location.href = 'http://server.new';
fakeWindow.setTimeout.flush();
expect(callback).toHaveBeenCalledWith('http://server.new');
fakeWindow.fire('popstate');
fakeWindow.fire('hashchange');
expect(callback).toHaveBeenCalledOnce();
});
});
it('should not fire urlChange if changed by browser.url method (polling)', function() {
sniffer.history = false;
sniffer.hashchange = false;
browser.onUrlChange(callback);
browser.url('http://new.com');
fakeWindow.setTimeout.flush();
expect(callback).not.toHaveBeenCalled();
});
it('should not fire urlChange if changed by browser.url method (hashchange)', function() {
sniffer.history = false;
sniffer.hashchange = true;
browser.onUrlChange(callback);
browser.url('http://new.com');
fakeWindow.fire('hashchange');
expect(callback).not.toHaveBeenCalled();
});
});
describe('baseHref', function() {
var jqDocHead;
beforeEach(function() {
jqDocHead = jqLite(document).find('head');
});
it('should return value from <base href>', function() {
fakeDocument.basePath = '/base/path/';
expect(browser.baseHref()).toEqual('/base/path/');
});
it('should return \'\' (empty string) if no <base href>', function() {
fakeDocument.basePath = undefined;
expect(browser.baseHref()).toEqual('');
});
it('should remove domain from <base href>', function() {
fakeDocument.basePath = 'http://host.com/base/path/';
expect(browser.baseHref()).toEqual('/base/path/');
fakeDocument.basePath = 'http://host.com/base/path/index.html';
expect(browser.baseHref()).toEqual('/base/path/index.html');
});
it('should remove domain from <base href> beginning with \'//\'', function() {
fakeDocument.basePath = '//google.com/base/path/';
expect(browser.baseHref()).toEqual('/base/path/');
});
});
describe('integration tests with $location', function() {
beforeEach(module(function($provide, $locationProvider) {
spyOn(fakeWindow.history, 'pushState').andCallFake(function(stateObj, title, newUrl) {
fakeWindow.location.href = newUrl;
});
$provide.value('$browser', browser);
browser.pollFns = [];
$locationProvider.html5Mode(true);
}));
it('should update $location when it was changed outside of Angular in sync '+
'before $digest was called', function() {
inject(function($rootScope, $location) {
fakeWindow.history.pushState(null, '', 'http://server/someTestHash');
// Verify that infinite digest reported in #6976 no longer occurs
expect(function() {
$rootScope.$digest();
}).not.toThrow();
expect($location.path()).toBe('/someTestHash');
});
});
});
});