aboutsummaryrefslogtreecommitdiffstats
path: root/test/service
diff options
context:
space:
mode:
Diffstat (limited to 'test/service')
-rw-r--r--test/service/cookieStoreSpec.js29
-rw-r--r--test/service/cookiesSpec.js97
-rw-r--r--test/service/deferSpec.js54
-rw-r--r--test/service/documentSpec.js16
-rw-r--r--test/service/exceptionHandlerSpec.js31
-rw-r--r--test/service/formFactorySpec.js71
-rw-r--r--test/service/locationSpec.js504
-rw-r--r--test/service/logSpec.js114
-rw-r--r--test/service/routeParamsSpec.js33
-rw-r--r--test/service/routeSpec.js202
-rw-r--r--test/service/scopeSpec.js524
-rw-r--r--test/service/windowSpec.js18
-rw-r--r--test/service/xhr.bulkSpec.js48
-rw-r--r--test/service/xhr.cacheSpec.js159
-rw-r--r--test/service/xhr.errorSpec.js27
-rw-r--r--test/service/xhrSpec.js166
16 files changed, 1023 insertions, 1070 deletions
diff --git a/test/service/cookieStoreSpec.js b/test/service/cookieStoreSpec.js
index 0bf7e99d..50ac7797 100644
--- a/test/service/cookieStoreSpec.js
+++ b/test/service/cookieStoreSpec.js
@@ -1,41 +1,30 @@
'use strict';
describe('$cookieStore', function() {
- var scope, $browser, $cookieStore;
- beforeEach(function() {
- scope = angular.scope();
- $cookieStore = scope.$service('$cookieStore');
- $browser = scope.$service('$browser');
- });
- afterEach(function() {
- dealoc(scope);
- });
-
-
- it('should serialize objects to json', function() {
+ it('should serialize objects to json', inject(function($cookieStore, $browser, $rootScope) {
$cookieStore.put('objectCookie', {id: 123, name: 'blah'});
- scope.$digest();
+ $rootScope.$digest();
expect($browser.cookies()).toEqual({'objectCookie': '{"id":123,"name":"blah"}'});
- });
+ }));
- it('should deserialize json to object', function() {
+ it('should deserialize json to object', inject(function($cookieStore, $browser) {
$browser.cookies('objectCookie', '{"id":123,"name":"blah"}');
$browser.poll();
expect($cookieStore.get('objectCookie')).toEqual({id: 123, name: 'blah'});
- });
+ }));
- it('should delete objects from the store when remove is called', function() {
+ it('should delete objects from the store when remove is called', inject(function($cookieStore, $browser, $rootScope) {
$cookieStore.put('gonner', { "I'll":"Be Back"});
- scope.$digest(); //force eval in test
+ $rootScope.$digest(); //force eval in test
$browser.poll();
expect($browser.cookies()).toEqual({'gonner': '{"I\'ll":"Be Back"}'});
$cookieStore.remove('gonner');
- scope.$digest();
+ $rootScope.$digest();
expect($browser.cookies()).toEqual({});
- });
+ }));
});
diff --git a/test/service/cookiesSpec.js b/test/service/cookiesSpec.js
index f078c20c..2569645b 100644
--- a/test/service/cookiesSpec.js
+++ b/test/service/cookiesSpec.js
@@ -1,82 +1,79 @@
'use strict';
describe('$cookies', function() {
- var scope, $browser;
-
- beforeEach(function() {
- $browser = new MockBrowser();
- $browser.cookieHash['preexisting'] = 'oldCookie';
- scope = angular.scope(angular.service, {$browser: $browser});
- scope.$cookies = scope.$service('$cookies');
- });
-
- afterEach(function() {
- dealoc(scope);
- });
-
+ beforeEach(inject(function(service) {
+ service('$browser', function(){
+ return angular.extend(new MockBrowser(), {cookieHash: {preexisting:'oldCookie'}});
+ });
+ }));
+
it('should provide access to existing cookies via object properties and keep them in sync',
- function() {
- expect(scope.$cookies).toEqual({'preexisting': 'oldCookie'});
+ inject(function($cookies, $browser, $rootScope) {
+ expect($cookies).toEqual({'preexisting': 'oldCookie'});
// access internal cookie storage of the browser mock directly to simulate behavior of
// document.cookie
$browser.cookieHash['brandNew'] = 'cookie';
$browser.poll();
- expect(scope.$cookies).toEqual({'preexisting': 'oldCookie', 'brandNew':'cookie'});
+ expect($cookies).toEqual({'preexisting': 'oldCookie', 'brandNew':'cookie'});
$browser.cookieHash['brandNew'] = 'cookie2';
$browser.poll();
- expect(scope.$cookies).toEqual({'preexisting': 'oldCookie', 'brandNew':'cookie2'});
+ expect($cookies).toEqual({'preexisting': 'oldCookie', 'brandNew':'cookie2'});
delete $browser.cookieHash['brandNew'];
$browser.poll();
- expect(scope.$cookies).toEqual({'preexisting': 'oldCookie'});
- });
+ expect($cookies).toEqual({'preexisting': 'oldCookie'});
+ }));
- it('should create or update a cookie when a value is assigned to a property', function() {
- scope.$cookies.oatmealCookie = 'nom nom';
- scope.$digest();
+ it('should create or update a cookie when a value is assigned to a property',
+ inject(function($cookies, $browser, $rootScope) {
+ $cookies.oatmealCookie = 'nom nom';
+ $rootScope.$digest();
expect($browser.cookies()).
toEqual({'preexisting': 'oldCookie', 'oatmealCookie':'nom nom'});
- scope.$cookies.oatmealCookie = 'gone';
- scope.$digest();
+ $cookies.oatmealCookie = 'gone';
+ $rootScope.$digest();
expect($browser.cookies()).
toEqual({'preexisting': 'oldCookie', 'oatmealCookie': 'gone'});
- });
+ }));
- it('should drop or reset any cookie that was set to a non-string value', function() {
- scope.$cookies.nonString = [1, 2, 3];
- scope.$cookies.nullVal = null;
- scope.$cookies.undefVal = undefined;
- scope.$cookies.preexisting = function() {};
- scope.$digest();
+ it('should drop or reset any cookie that was set to a non-string value',
+ inject(function($cookies, $browser, $rootScope) {
+ $cookies.nonString = [1, 2, 3];
+ $cookies.nullVal = null;
+ $cookies.undefVal = undefined;
+ $cookies.preexisting = function() {};
+ $rootScope.$digest();
expect($browser.cookies()).toEqual({'preexisting': 'oldCookie'});
- expect(scope.$cookies).toEqual({'preexisting': 'oldCookie'});
- });
+ expect($cookies).toEqual({'preexisting': 'oldCookie'});
+ }));
- it('should remove a cookie when a $cookies property is deleted', function() {
- scope.$cookies.oatmealCookie = 'nom nom';
- scope.$digest();
+ it('should remove a cookie when a $cookies property is deleted',
+ inject(function($cookies, $browser, $rootScope) {
+ $cookies.oatmealCookie = 'nom nom';
+ $rootScope.$digest();
$browser.poll();
expect($browser.cookies()).
toEqual({'preexisting': 'oldCookie', 'oatmealCookie':'nom nom'});
- delete scope.$cookies.oatmealCookie;
- scope.$digest();
+ delete $cookies.oatmealCookie;
+ $rootScope.$digest();
expect($browser.cookies()).toEqual({'preexisting': 'oldCookie'});
- });
+ }));
- it('should drop or reset cookies that browser refused to store', function() {
+ it('should drop or reset cookies that browser refused to store',
+ inject(function($cookies, $browser, $rootScope) {
var i, longVal;
for (i=0; i<5000; i++) {
@@ -84,17 +81,17 @@ describe('$cookies', function() {
}
//drop if no previous value
- scope.$cookies.longCookie = longVal;
- scope.$digest();
- expect(scope.$cookies).toEqual({'preexisting': 'oldCookie'});
+ $cookies.longCookie = longVal;
+ $rootScope.$digest();
+ expect($cookies).toEqual({'preexisting': 'oldCookie'});
//reset if previous value existed
- scope.$cookies.longCookie = 'shortVal';
- scope.$digest();
- expect(scope.$cookies).toEqual({'preexisting': 'oldCookie', 'longCookie': 'shortVal'});
- scope.$cookies.longCookie = longVal;
- scope.$digest();
- expect(scope.$cookies).toEqual({'preexisting': 'oldCookie', 'longCookie': 'shortVal'});
- });
+ $cookies.longCookie = 'shortVal';
+ $rootScope.$digest();
+ expect($cookies).toEqual({'preexisting': 'oldCookie', 'longCookie': 'shortVal'});
+ $cookies.longCookie = longVal;
+ $rootScope.$digest();
+ expect($cookies).toEqual({'preexisting': 'oldCookie', 'longCookie': 'shortVal'});
+ }));
});
diff --git a/test/service/deferSpec.js b/test/service/deferSpec.js
index ff48c93e..98ddeac5 100644
--- a/test/service/deferSpec.js
+++ b/test/service/deferSpec.js
@@ -1,22 +1,14 @@
'use strict';
describe('$defer', function() {
- var scope, $browser, $defer, $exceptionHandler;
-
- beforeEach(function() {
- scope = angular.scope(angular.service,
- {'$exceptionHandler': jasmine.createSpy('$exceptionHandler')});
- $browser = scope.$service('$browser');
- $defer = scope.$service('$defer');
- $exceptionHandler = scope.$service('$exceptionHandler');
- });
-
- afterEach(function() {
- dealoc(scope);
- });
+ beforeEach(inject(function(service) {
+ service('$exceptionHandler', function(){
+ return jasmine.createSpy('$exceptionHandler');
+ });
+ }));
- it('should delegate functions to $browser.defer', function() {
+ it('should delegate functions to $browser.defer', inject(function($defer, $browser, $exceptionHandler) {
var counter = 0;
$defer(function() { counter++; });
@@ -29,20 +21,20 @@ describe('$defer', function() {
expect(counter).toBe(1);
expect($exceptionHandler).not.toHaveBeenCalled();
- });
+ }));
- it('should delegate exception to the $exceptionHandler service', function() {
+ it('should delegate exception to the $exceptionHandler service', inject(function($defer, $browser, $exceptionHandler) {
$defer(function() {throw "Test Error";});
expect($exceptionHandler).not.toHaveBeenCalled();
$browser.defer.flush();
expect($exceptionHandler).toHaveBeenCalledWith("Test Error");
- });
+ }));
- it('should call $apply after each callback is executed', function() {
- var applySpy = this.spyOn(scope, '$apply').andCallThrough();
+ it('should call $apply after each callback is executed', inject(function($defer, $browser, $rootScope) {
+ var applySpy = this.spyOn($rootScope, '$apply').andCallThrough();
$defer(function() {});
expect(applySpy).not.toHaveBeenCalled();
@@ -56,36 +48,36 @@ describe('$defer', function() {
$defer(function() {});
$browser.defer.flush();
expect(applySpy.callCount).toBe(2);
- });
+ }));
- it('should call $apply even if an exception is thrown in callback', function() {
- var applySpy = this.spyOn(scope, '$apply').andCallThrough();
+ it('should call $apply even if an exception is thrown in callback', inject(function($defer, $browser, $rootScope) {
+ var applySpy = this.spyOn($rootScope, '$apply').andCallThrough();
$defer(function() {throw "Test Error";});
expect(applySpy).not.toHaveBeenCalled();
$browser.defer.flush();
expect(applySpy).toHaveBeenCalled();
- });
+ }));
- it('should allow you to specify the delay time', function() {
+ it('should allow you to specify the delay time', inject(function($defer, $browser) {
var defer = this.spyOn($browser, 'defer');
$defer(noop, 123);
expect(defer.callCount).toEqual(1);
expect(defer.mostRecentCall.args[1]).toEqual(123);
- });
+ }));
- it('should return a cancelation token', function() {
+ it('should return a cancelation token', inject(function($defer, $browser) {
var defer = this.spyOn($browser, 'defer').andReturn('xxx');
expect($defer(noop)).toEqual('xxx');
- });
+ }));
describe('cancel', function() {
- it('should cancel tasks', function() {
+ it('should cancel tasks', inject(function($defer, $browser) {
var task1 = jasmine.createSpy('task1'),
task2 = jasmine.createSpy('task2'),
task3 = jasmine.createSpy('task3'),
@@ -102,10 +94,10 @@ describe('$defer', function() {
expect(task1).not.toHaveBeenCalled();
expect(task2).toHaveBeenCalledOnce();
expect(task3).not.toHaveBeenCalled();
- });
+ }));
- it('should return true if a task was succesffuly canceled', function() {
+ it('should return true if a task was succesffuly canceled', inject(function($defer, $browser) {
var task1 = jasmine.createSpy('task1'),
task2 = jasmine.createSpy('task2'),
token1, token2;
@@ -116,6 +108,6 @@ describe('$defer', function() {
expect($defer.cancel(token1)).toBe(false);
expect($defer.cancel(token2)).toBe(true);
- });
+ }));
});
});
diff --git a/test/service/documentSpec.js b/test/service/documentSpec.js
index 885331e4..064904a2 100644
--- a/test/service/documentSpec.js
+++ b/test/service/documentSpec.js
@@ -1,19 +1,9 @@
'use strict';
describe('$document', function() {
- var scope;
- beforeEach(function() {
- scope = angular.scope();
- });
-
- afterEach(function() {
- dealoc(scope);
- });
-
-
- it("should inject $document", function() {
- expect(scope.$service('$document')).toEqual(jqLite(document));
- });
+ it("should inject $document", inject(function($document) {
+ expect($document).toEqual(jqLite(document));
+ }));
});
diff --git a/test/service/exceptionHandlerSpec.js b/test/service/exceptionHandlerSpec.js
index 61e652b5..3bfb70c0 100644
--- a/test/service/exceptionHandlerSpec.js
+++ b/test/service/exceptionHandlerSpec.js
@@ -1,26 +1,17 @@
'use strict';
describe('$exceptionHandler', function() {
- var scope;
- beforeEach(function() {
- scope = angular.scope();
- });
-
- afterEach(function() {
- dealoc(scope);
- });
-
-
- it('should log errors', function() {
- var scope = createScope({$exceptionHandler: $exceptionHandlerFactory},
- {$log: $logMock}),
- $log = scope.$service('$log'),
- $exceptionHandler = scope.$service('$exceptionHandler');
-
- $log.error.rethrow = false;
- $exceptionHandler('myError');
- expect($log.error.logs.shift()).toEqual(['myError']);
- });
+ it('should log errors', inject(
+ function(service){
+ service('$exceptionHandler', $exceptionHandlerFactory);
+ service('$log', valueFn($logMock));
+ },
+ function($log, $exceptionHandler) {
+ $log.error.rethrow = false;
+ $exceptionHandler('myError');
+ expect($log.error.logs.shift()).toEqual(['myError']);
+ }
+ ));
});
diff --git a/test/service/formFactorySpec.js b/test/service/formFactorySpec.js
index 23b8ae0a..fbe601c6 100644
--- a/test/service/formFactorySpec.js
+++ b/test/service/formFactorySpec.js
@@ -2,19 +2,10 @@
describe('$formFactory', function() {
- var rootScope;
- var formFactory;
-
- beforeEach(function() {
- rootScope = angular.scope();
- formFactory = rootScope.$service('$formFactory');
- });
-
-
- it('should have global form', function() {
- expect(formFactory.rootForm).toBeTruthy();
- expect(formFactory.rootForm.$createWidget).toBeTruthy();
- });
+ it('should have global form', inject(function($rootScope, $formFactory) {
+ expect($formFactory.rootForm).toBeTruthy();
+ expect($formFactory.rootForm.$createWidget).toBeTruthy();
+ }));
describe('new form', function() {
@@ -41,11 +32,11 @@ describe('$formFactory', function() {
}
};
- beforeEach(function() {
+ beforeEach(inject(function($rootScope, $formFactory) {
log = '';
- scope = rootScope.$new();
- form = formFactory(scope);
- });
+ scope = $rootScope.$new();
+ form = $formFactory(scope);
+ }));
describe('$createWidget', function() {
var widget;
@@ -61,14 +52,14 @@ describe('$formFactory', function() {
describe('data flow', function() {
- it('should have status properties', function() {
+ it('should have status properties', inject(function($rootScope, $formFactory) {
expect(widget.$error).toEqual({});
expect(widget.$valid).toBe(true);
expect(widget.$invalid).toBe(false);
- });
+ }));
- it('should update view when model changes', function() {
+ it('should update view when model changes', inject(function($rootScope, $formFactory) {
scope.text = 'abc';
scope.$digest();
expect(log).toEqual('<init>$validate();$render();');
@@ -78,17 +69,17 @@ describe('$formFactory', function() {
scope.$digest();
expect(widget.$modelValue).toEqual('xyz');
- });
+ }));
- it('should have controller prototype methods', function() {
- expect(widget.getFormFactory()).toEqual(formFactory);
- });
+ it('should have controller prototype methods', inject(function($rootScope, $formFactory) {
+ expect(widget.getFormFactory()).toEqual($formFactory);
+ }));
});
describe('validation', function() {
- it('should update state on error', function() {
+ it('should update state on error', inject(function($rootScope, $formFactory) {
widget.$emit('$invalid', 'E');
expect(widget.$valid).toEqual(false);
expect(widget.$invalid).toEqual(true);
@@ -96,21 +87,21 @@ describe('$formFactory', function() {
widget.$emit('$valid', 'E');
expect(widget.$valid).toEqual(true);
expect(widget.$invalid).toEqual(false);
- });
+ }));
- it('should have called the model setter before the validation', function() {
+ it('should have called the model setter before the validation', inject(function($rootScope, $formFactory) {
var modelValue;
widget.$on('$validate', function() {
modelValue = scope.text;
});
widget.$emit('$viewChange', 'abc');
expect(modelValue).toEqual('abc');
- });
+ }));
describe('form', function() {
- it('should invalidate form when widget is invalid', function() {
+ it('should invalidate form when widget is invalid', inject(function($rootScope, $formFactory) {
expect(form.$error).toEqual({});
expect(form.$valid).toEqual(true);
expect(form.$invalid).toEqual(false);
@@ -143,18 +134,18 @@ describe('$formFactory', function() {
expect(form.$error).toEqual({});
expect(form.$valid).toEqual(true);
expect(form.$invalid).toEqual(false);
- });
+ }));
});
});
describe('id assignment', function() {
- it('should default to name expression', function() {
+ it('should default to name expression', inject(function($rootScope, $formFactory) {
expect(form.text).toEqual(widget);
- });
+ }));
- it('should use ng:id', function() {
+ it('should use ng:id', inject(function($rootScope, $formFactory) {
widget = form.$createWidget({
scope:scope,
model:'text',
@@ -162,10 +153,10 @@ describe('$formFactory', function() {
controller:WidgetCtrl
});
expect(form['my.id']).toEqual(widget);
- });
+ }));
- it('should not override existing names', function() {
+ it('should not override existing names', inject(function($rootScope, $formFactory) {
var widget2 = form.$createWidget({
scope:scope,
model:'text',
@@ -174,11 +165,11 @@ describe('$formFactory', function() {
});
expect(form.text).toEqual(widget);
expect(widget2).not.toEqual(widget);
- });
+ }));
});
describe('dealocation', function() {
- it('should dealocate', function() {
+ it('should dealocate', inject(function($rootScope, $formFactory) {
var widget2 = form.$createWidget({
scope:scope,
model:'text',
@@ -199,10 +190,10 @@ describe('$formFactory', function() {
widget2.$destroy();
expect(form.myId).toBeUndefined();
- });
+ }));
- it('should remove invalid fields from errors, when child widget removed', function() {
+ it('should remove invalid fields from errors, when child widget removed', inject(function($rootScope, $formFactory) {
widget.$emit('$invalid', 'MyError');
expect(form.$error.MyError).toEqual([widget]);
@@ -212,7 +203,7 @@ describe('$formFactory', function() {
expect(form.$error.MyError).toBeUndefined();
expect(form.$invalid).toEqual(false);
- });
+ }));
});
});
});
diff --git a/test/service/locationSpec.js b/test/service/locationSpec.js
index 9a7aa943..38df2619 100644
--- a/test/service/locationSpec.js
+++ b/test/service/locationSpec.js
@@ -307,164 +307,187 @@ describe('$location', function() {
});
- var $browser, $location, scope;
-
- function init(url, html5Mode, basePath, hashPrefix, supportHistory) {
- scope = angular.scope(null, {
- $locationConfig: {html5Mode: html5Mode, hashPrefix: hashPrefix},
- $sniffer: {history: supportHistory}});
-
- $browser = scope.$service('$browser');
- $browser.url(url);
- $browser.$$baseHref = basePath;
- $location = scope.$service('$location');
+ function initService(html5Mode, hashPrefix, supportHistory) {
+ return function(service){
+ service('$locationConfig', function(){
+ return {html5Mode: html5Mode, hashPrefix: hashPrefix};
+ });
+ service('$sniffer', function(){
+ return {history: supportHistory};
+ });
+ };
}
-
- function dealocRootElement() {
- dealoc(scope.$service('$document'));
+ function initBrowser(url, basePath) {
+ return function($browser){
+ $browser.url(url);
+ $browser.$$baseHref = basePath;
+ };
}
-
describe('wiring', function() {
- beforeEach(function() {
- init('http://new.com/a/b#!', false, '/a/b', '!', true);
- });
+ beforeEach(inject(initService(false, '!', true), initBrowser('http://new.com/a/b#!', '/a/b')));
- it('should update $location when browser url changes', function() {
+ it('should update $location when browser url changes', inject(function($browser, $location) {
spyOn($location, '$$parse').andCallThrough();
$browser.url('http://new.com/a/b#!/aaa');
$browser.poll();
expect($location.absUrl()).toBe('http://new.com/a/b#!/aaa');
expect($location.path()).toBe('/aaa');
expect($location.$$parse).toHaveBeenCalledOnce();
- });
+ }));
- it('should update browser when $location changes', function() {
+ it('should update browser when $location changes', inject(function($rootScope, $browser, $location) {
var $browserUrl = spyOnlyCallsWithArgs($browser, 'url').andCallThrough();
$location.path('/new/path');
expect($browserUrl).not.toHaveBeenCalled();
- scope.$apply();
+ $rootScope.$apply();
expect($browserUrl).toHaveBeenCalledOnce();
expect($browser.url()).toBe('http://new.com/a/b#!/new/path');
- });
+ }));
- it('should update browser only once per $apply cycle', function() {
+ it('should update browser only once per $apply cycle', inject(function($rootScope, $browser, $location) {
var $browserUrl = spyOnlyCallsWithArgs($browser, 'url').andCallThrough();
$location.path('/new/path');
- scope.$watch(function() {
+ $rootScope.$watch(function() {
$location.search('a=b');
});
- scope.$apply();
+ $rootScope.$apply();
expect($browserUrl).toHaveBeenCalledOnce();
expect($browser.url()).toBe('http://new.com/a/b#!/new/path?a=b');
- });
+ }));
- it('should replace browser url when url was replaced at least once', function() {
+ it('should replace browser url when url was replaced at least once',
+ inject(function($rootScope, $location, $browser) {
var $browserUrl = spyOnlyCallsWithArgs($browser, 'url').andCallThrough();
$location.path('/n/url').replace();
- scope.$apply();
+ $rootScope.$apply();
expect($browserUrl).toHaveBeenCalledOnce();
expect($browserUrl.mostRecentCall.args).toEqual(['http://new.com/a/b#!/n/url', true]);
- });
+ }));
- it('should update the browser if changed from within a watcher', function() {
- scope.$watch(function() { return true; }, function() {
+ it('should update the browser if changed from within a watcher', inject(function($rootScope, $location, $browser) {
+ $rootScope.$watch(function() { return true; }, function() {
$location.path('/changed');
});
- scope.$digest();
+ $rootScope.$digest();
expect($browser.url()).toBe('http://new.com/a/b#!/changed');
- });
+ }));
});
// html5 history is disabled
describe('disabled history', function() {
- it('should use hashbang url with hash prefix', function() {
- init('http://domain.com/base/index.html#!/a/b', false, '/base/index.html', '!');
- expect($browser.url()).toBe('http://domain.com/base/index.html#!/a/b');
- $location.path('/new');
- $location.search({a: true});
- scope.$apply();
- expect($browser.url()).toBe('http://domain.com/base/index.html#!/new?a');
- });
-
-
- it('should use hashbang url without hash prefix', function() {
- init('http://domain.com/base/index.html#/a/b', false, '/base/index.html', '');
- expect($browser.url()).toBe('http://domain.com/base/index.html#/a/b');
- $location.path('/new');
- $location.search({a: true});
- scope.$apply();
- expect($browser.url()).toBe('http://domain.com/base/index.html#/new?a');
- });
+ it('should use hashbang url with hash prefix', inject(
+ initService(false, '!'),
+ initBrowser('http://domain.com/base/index.html#!/a/b', '/base/index.html'),
+ function($rootScope, $location, $browser) {
+ expect($browser.url()).toBe('http://domain.com/base/index.html#!/a/b');
+ $location.path('/new');
+ $location.search({a: true});
+ $rootScope.$apply();
+ expect($browser.url()).toBe('http://domain.com/base/index.html#!/new?a');
+ })
+ );
+
+
+ it('should use hashbang url without hash prefix', inject(
+ initService(false, ''),
+ initBrowser('http://domain.com/base/index.html#/a/b', '/base/index.html'),
+ function($rootScope, $location, $browser) {
+ expect($browser.url()).toBe('http://domain.com/base/index.html#/a/b');
+ $location.path('/new');
+ $location.search({a: true});
+ $rootScope.$apply();
+ expect($browser.url()).toBe('http://domain.com/base/index.html#/new?a');
+ })
+ );
});
// html5 history enabled, but not supported by browser
describe('history on old browser', function() {
- afterEach(dealocRootElement);
-
- it('should use hashbang url with hash prefix', function() {
- init('http://domain.com/base/index.html#!!/a/b', true, '/base/index.html', '!!', false);
- expect($browser.url()).toBe('http://domain.com/base/index.html#!!/a/b');
- $location.path('/new');
- $location.search({a: true});
- scope.$apply();
- expect($browser.url()).toBe('http://domain.com/base/index.html#!!/new?a');
- });
-
-
- it('should redirect to hashbang url when new url given', function() {
- init('http://domain.com/base/new-path/index.html', true, '/base/index.html', '!');
- expect($browser.url()).toBe('http://domain.com/base/index.html#!/new-path/index.html');
- });
+ afterEach(inject(function($document){
+ dealoc($document);
+ }));
+
+ it('should use hashbang url with hash prefix', inject(
+ initService(true, '!!', false),
+ initBrowser('http://domain.com/base/index.html#!!/a/b', '/base/index.html'),
+ function($rootScope, $location, $browser) {
+ expect($browser.url()).toBe('http://domain.com/base/index.html#!!/a/b');
+ $location.path('/new');
+ $location.search({a: true});
+ $rootScope.$apply();
+ expect($browser.url()).toBe('http://domain.com/base/index.html#!!/new?a');
+ })
+ );
+
+
+ it('should redirect to hashbang url when new url given', inject(
+ initService(true, '!'),
+ initBrowser('http://domain.com/base/new-path/index.html', '/base/index.html'),
+ function($browser, $location) {
+ expect($browser.url()).toBe('http://domain.com/base/index.html#!/new-path/index.html');
+ })
+ );
});
// html5 history enabled and supported by browser
describe('history on new browser', function() {
- afterEach(dealocRootElement);
-
- it('should use new url', function() {
- init('http://domain.com/base/old/index.html#a', true, '/base/index.html', '', true);
- expect($browser.url()).toBe('http://domain.com/base/old/index.html#a');
- $location.path('/new');
- $location.search({a: true});
- scope.$apply();
- expect($browser.url()).toBe('http://domain.com/base/new?a#a');
- });
-
-
- it('should rewrite when hashbang url given', function() {
- init('http://domain.com/base/index.html#!/a/b', true, '/base/index.html', '!', true);
- expect($browser.url()).toBe('http://domain.com/base/a/b');
- $location.path('/new');
- $location.hash('abc');
- scope.$apply();
- expect($browser.url()).toBe('http://domain.com/base/new#abc');
- expect($location.path()).toBe('/new');
- });
-
-
- it('should rewrite when hashbang url given (without hash prefix)', function() {
- init('http://domain.com/base/index.html#/a/b', true, '/base/index.html', '', true);
- expect($browser.url()).toBe('http://domain.com/base/a/b');
- expect($location.path()).toBe('/a/b');
- });
+ afterEach(inject(function($document){
+ dealoc($document);
+ }));
+
+ it('should use new url', inject(
+ initService(true, '', true),
+ initBrowser('http://domain.com/base/old/index.html#a', '/base/index.html'),
+ function($rootScope, $location, $browser) {
+ expect($browser.url()).toBe('http://domain.com/base/old/index.html#a');
+ $location.path('/new');
+ $location.search({a: true});
+ $rootScope.$apply();
+ expect($browser.url()).toBe('http://domain.com/base/new?a#a');
+ })
+ );
+
+
+ it('should rewrite when hashbang url given', inject(
+ initService(true, '!', true),
+ initBrowser('http://domain.com/base/index.html#!/a/b', '/base/index.html'),
+ function($rootScope, $location, $browser) {
+ expect($browser.url()).toBe('http://domain.com/base/a/b');
+ $location.path('/new');
+ $location.hash('abc');
+ $rootScope.$apply();
+ expect($browser.url()).toBe('http://domain.com/base/new#abc');
+ expect($location.path()).toBe('/new');
+ })
+ );
+
+
+ it('should rewrite when hashbang url given (without hash prefix)', inject(
+ initService(true, '', true),
+ initBrowser('http://domain.com/base/index.html#/a/b', '/base/index.html'),
+ function($rootScope, $location, $browser) {
+ expect($browser.url()).toBe('http://domain.com/base/a/b');
+ expect($location.path()).toBe('/a/b');
+ })
+ );
});
@@ -554,43 +577,48 @@ describe('$location', function() {
describe('link rewriting', function() {
- var root, link, extLink, $browser, originalBrowser, lastEventPreventDefault;
+ var root, link, originalBrowser, lastEventPreventDefault;
- function init(linkHref, html5Mode, supportHist, attrs, content) {
- var jqRoot = jqLite('<div></div>');
- attrs = attrs ? ' ' + attrs + ' ' : '';
- content = content || 'link';
- link = jqLite('<a href="' + linkHref + '"' + attrs + '>' + content + '</a>')[0];
- root = jqRoot.append(link)[0];
+ function configureService(linkHref, html5Mode, supportHist, attrs, content) {
+ return function(service){
+ var jqRoot = jqLite('<div></div>');
+ attrs = attrs ? ' ' + attrs + ' ' : '';
+ link = jqLite('<a href="' + linkHref + '"' + attrs + '>' + content + '</a>')[0];
+ root = jqRoot.append(link)[0];
- jqLite(document.body).append(jqRoot);
+ jqLite(document.body).append(jqRoot);
- var scope = angular.scope(null, {
- $document: jqRoot,
- $sniffer: {history: supportHist},
- $locationConfig: {html5Mode: html5Mode, hashPrefix: '!'}
- });
+ service('$document', function(){ return jqRoot; });
+ service('$sniffer', function(){ return {history: supportHist}; });
+ service('$locationConfig', function(){ return {html5Mode: html5Mode, hashPrefix: '!'}; });
+ };
+ }
- $browser = scope.$service('$browser');
- $browser.url('http://host.com/base');
- $browser.$$baseHref = '/base/index.html';
- var $location = scope.$service('$location');
- originalBrowser = $browser.url();
-
- // we have to prevent the default operation, as we need to test absolute links (http://...)
- // and navigating to these links would kill jstd
- jqRoot.bind('click', function(e) {
- lastEventPreventDefault = e.isDefaultPrevented();
- e.preventDefault();
- });
+ function initBrowser() {
+ return function($browser){
+ $browser.url('http://host.com/base');
+ $browser.$$baseHref = '/base/index.html';
+ };
+ }
+
+ function initLocation() {
+ return function($browser, $location, $document) {
+ originalBrowser = $browser.url();
+ // we have to prevent the default operation, as we need to test absolute links (http://...)
+ // and navigating to these links would kill jstd
+ $document.bind('click', function(e) {
+ lastEventPreventDefault = e.isDefaultPrevented();
+ e.preventDefault();
+ });
+ };
}
- function expectRewriteTo(url) {
+ function expectRewriteTo($browser, url) {
expect(lastEventPreventDefault).toBe(true);
expect($browser.url()).toBe(url);
}
- function expectNoRewrite() {
+ function expectNoRewrite($browser) {
expect(lastEventPreventDefault).toBe(false);
expect($browser.url()).toBe(originalBrowser);
}
@@ -601,100 +629,152 @@ describe('$location', function() {
});
- it('should rewrite rel link to new url when history enabled on new browser', function() {
- init('link?a#b', true, true);
- browserTrigger(link, 'click');
- expectRewriteTo('http://host.com/base/link?a#b');
- });
-
-
- it('should rewrite abs link to new url when history enabled on new browser', function() {
- init('/base/link?a#b', true, true);
- browserTrigger(link, 'click');
- expectRewriteTo('http://host.com/base/link?a#b');
- });
-
-
- it('should rewrite rel link to hashbang url when history enabled on old browser', function() {
- init('link?a#b', true, false);
- browserTrigger(link, 'click');
- expectRewriteTo('http://host.com/base/index.html#!/link?a#b');
- });
-
-
- it('should rewrite abs link to hashbang url when history enabled on old browser', function() {
- init('/base/link?a#b', true, false);
- browserTrigger(link, 'click');
- expectRewriteTo('http://host.com/base/index.html#!/link?a#b');
- });
-
-
- it('should not rewrite when history disabled', function() {
- init('#new', false);
- browserTrigger(link, 'click');
- expectNoRewrite();
- });
-
-
- it('should not rewrite ng:ext-link', function() {
- init('#new', true, true, 'ng:ext-link');
- browserTrigger(link, 'click');
- expectNoRewrite();
- });
-
-
- it('should not rewrite full url links do different domain', function() {
- init('http://www.dot.abc/a?b=c', true);
- browserTrigger(link, 'click');
- expectNoRewrite();
- });
-
-
- it('should not rewrite links with target="_blank"', function() {
- init('/a?b=c', true, true, 'target="_blank"');
- browserTrigger(link, 'click');
- expectNoRewrite();
- });
-
-
- it('should not rewrite links with target specified', function() {
- init('/a?b=c', true, true, 'target="some-frame"');
- browserTrigger(link, 'click');
- expectNoRewrite();
- });
-
-
- it('should rewrite full url links to same domain and base path', function() {
- init('http://host.com/base/new', true);
- browserTrigger(link, 'click');
- expectRewriteTo('http://host.com/base/index.html#!/new');
- });
-
-
- it('should rewrite when clicked span inside link', function() {
- init('some/link', true, true, '', '<span>link</span>');
- var span = jqLite(link).find('span');
-
- browserTrigger(span, 'click');
- expectRewriteTo('http://host.com/base/some/link');
- });
+ it('should rewrite rel link to new url when history enabled on new browser', inject(
+ configureService('link?a#b', true, true),
+ initBrowser(),
+ initLocation(),
+ function($browser) {
+ browserTrigger(link, 'click');
+ expectRewriteTo($browser, 'http://host.com/base/link?a#b');
+ })
+ );
+
+
+ it('should rewrite abs link to new url when history enabled on new browser', inject(
+ configureService('/base/link?a#b', true, true),
+ initBrowser(),
+ initLocation(),
+ function($browser) {
+ browserTrigger(link, 'click');
+ expectRewriteTo($browser, 'http://host.com/base/link?a#b');
+ })
+ );
+
+
+ it('should rewrite rel link to hashbang url when history enabled on old browser', inject(
+ configureService('link?a#b', true, false),
+ initBrowser(),
+ initLocation(),
+ function($browser) {
+ browserTrigger(link, 'click');
+ expectRewriteTo($browser, 'http://host.com/base/index.html#!/link?a#b');
+ })
+ );
+
+
+ it('should rewrite abs link to hashbang url when history enabled on old browser', inject(
+ configureService('/base/link?a#b', true, false),
+ initBrowser(),
+ initLocation(),
+ function($browser) {
+ browserTrigger(link, 'click');
+ expectRewriteTo($browser, 'http://host.com/base/index.html#!/link?a#b');
+ })
+ );
+
+
+ it('should not rewrite when history disabled', inject(
+ configureService('#new', false),
+ initBrowser(),
+ initLocation(),
+ function($browser) {
+ browserTrigger(link, 'click');
+ expectNoRewrite($browser);
+ })
+ );
+
+
+ it('should not rewrite ng:ext-link', inject(
+ configureService('#new', true, true, 'ng:ext-link'),
+ initBrowser(),
+ initLocation(),
+ function($browser) {
+ browserTrigger(link, 'click');
+ expectNoRewrite($browser);
+ })
+ );
+
+
+ it('should not rewrite full url links do different domain', inject(
+ configureService('http://www.dot.abc/a?b=c', true),
+ initBrowser(),
+ initLocation(),
+ function($browser) {
+ browserTrigger(link, 'click');
+ expectNoRewrite($browser);
+ })
+ );
+
+
+ it('should not rewrite links with target="_blank"', inject(
+ configureService('/a?b=c', true, true, 'target="_blank"'),
+ initBrowser(),
+ initLocation(),
+ function($browser) {
+ browserTrigger(link, 'click');
+ expectNoRewrite($browser);
+ })
+ );
+
+
+ it('should not rewrite links with target specified', inject(
+ configureService('/a?b=c', true, true, 'target="some-frame"'),
+ initBrowser(),
+ initLocation(),
+ function($browser) {
+ browserTrigger(link, 'click');
+ expectNoRewrite($browser);
+ })
+ );
+
+
+ it('should rewrite full url links to same domain and base path', inject(
+ configureService('http://host.com/base/new', true),
+ initBrowser(),
+ initLocation(),
+ function($browser) {
+ browserTrigger(link, 'click');
+ expectRewriteTo($browser, 'http://host.com/base/index.html#!/new');
+ })
+ );
+
+
+ it('should rewrite when clicked span inside link', inject(
+ configureService('some/link', true, true, '', '<span>link</span>'),
+ initBrowser(),
+ initLocation(),
+ function($browser) {
+ var span = jqLite(link).find('span');
+
+ browserTrigger(span, 'click');
+ expectRewriteTo($browser, 'http://host.com/base/some/link');
+ })
+ );
// don't run next tests on IE<9, as browserTrigger does not simulate pressed keys
if (!(msie < 9)) {
- it('should not rewrite when clicked with ctrl pressed', function() {
- init('/a?b=c', true, true);
- browserTrigger(link, 'click', ['ctrl']);
- expectNoRewrite();
- });
-
-
- it('should not rewrite when clicked with meta pressed', function() {
- init('/a?b=c', true, true);
- browserTrigger(link, 'click', ['meta']);
- expectNoRewrite();
- });
+ it('should not rewrite when clicked with ctrl pressed', inject(
+ configureService('/a?b=c', true, true),
+ initBrowser(),
+ initLocation(),
+ function($browser) {
+ browserTrigger(link, 'click', ['ctrl']);
+ expectNoRewrite($browser);
+ })
+ );
+
+
+ it('should not rewrite when clicked with meta pressed', inject(
+ configureService('/a?b=c', true, true),
+ initBrowser(),
+ initLocation(),
+ function($browser) {
+ browserTrigger(link, 'click', ['meta']);
+ expectNoRewrite($browser);
+ })
+ );
}
});
});
diff --git a/test/service/logSpec.js b/test/service/logSpec.js
index c4efb8c5..8c56d99e 100644
--- a/test/service/logSpec.js
+++ b/test/service/logSpec.js
@@ -1,65 +1,61 @@
'use strict';
describe('$log', function() {
- var scope;
-
- beforeEach(function() {
- scope = angular.scope();
- });
-
-
- afterEach(function() {
- dealoc(scope);
- });
-
-
- it('should use console if present', function() {
- var logger = "";
- function log() { logger+= 'log;'; }
- function warn() { logger+= 'warn;'; }
- function info() { logger+= 'info;'; }
- function error() { logger+= 'error;'; }
- var scope = createScope({$log: $logFactory},
- {$exceptionHandler: rethrow,
- $window: {console: {log: log,
- warn: warn,
- info: info,
- error: error}}}),
- $log = scope.$service('$log');
-
- $log.log();
- $log.warn();
- $log.info();
- $log.error();
- expect(logger).toEqual('log;warn;info;error;');
- });
-
-
- it('should use console.log() if other not present', function() {
- var logger = "";
- function log() { logger+= 'log;'; }
- var scope = createScope({$log: $logFactory},
- {$window: {console:{log:log}},
- $exceptionHandler: rethrow});
- var $log = scope.$service('$log');
- $log.log();
- $log.warn();
- $log.info();
- $log.error();
- expect(logger).toEqual('log;log;log;log;');
- });
-
-
- it('should use noop if no console', function() {
- var scope = createScope({$log: $logFactory},
- {$window: {},
- $exceptionHandler: rethrow}),
- $log = scope.$service('$log');
- $log.log();
- $log.warn();
- $log.info();
- $log.error();
- });
+ var $window;
+ var logger;
+
+ function log() { logger+= 'log;'; }
+ function warn() { logger+= 'warn;'; }
+ function info() { logger+= 'info;'; }
+ function error() { logger+= 'error;'; }
+
+ beforeEach(inject(function(service){
+ $window = {};
+ logger = '';
+ service('$log', $logFactory);
+ service('$exceptionHandler', valueFn(rethrow));
+ service('$window', valueFn($window));
+ }));
+
+ it('should use console if present', inject(
+ function(){
+ $window.console = {log: log,
+ warn: warn,
+ info: info,
+ error: error};
+ },
+ function($log) {
+ $log.log();
+ $log.warn();
+ $log.info();
+ $log.error();
+ expect(logger).toEqual('log;warn;info;error;');
+ }
+ ));
+
+
+ it('should use console.log() if other not present', inject(
+ function(){
+ $window.console = {log: log};
+ },
+ function($log) {
+ $log.log();
+ $log.warn();
+ $log.info();
+ $log.error();
+ expect(logger).toEqual('log;log;log;log;');
+ }
+ ));
+
+
+ it('should use noop if no console', inject(
+ function($log) {
+ $log.log();
+ $log.warn();
+ $log.info();
+ $log.error();
+ }
+ ));
describe('$log.error', function() {
diff --git a/test/service/routeParamsSpec.js b/test/service/routeParamsSpec.js
index 972e4314..d4088767 100644
--- a/test/service/routeParamsSpec.js
+++ b/test/service/routeParamsSpec.js
@@ -1,41 +1,16 @@
'use strict';
describe('$routeParams', function() {
- it('should publish the params into a service', function() {
- var scope = angular.scope(),
- $location = scope.$service('$location'),
- $route = scope.$service('$route'),
- $routeParams = scope.$service('$routeParams');
-
+ it('should publish the params into a service', inject(function($rootScope, $route, $location, $routeParams) {
$route.when('/foo');
$route.when('/bar/:barId');
$location.path('/foo').search('a=b');
- scope.$digest();
+ $rootScope.$digest();
expect($routeParams).toEqual({a:'b'});
$location.path('/bar/123').search('x=abc');
- scope.$digest();
+ $rootScope.$digest();
expect($routeParams).toEqual({barId:'123', x:'abc'});
- });
-
-
- it('should preserve object identity during route reloads', function() {
- var scope = angular.scope(),
- $location = scope.$service('$location'),
- $route = scope.$service('$route'),
- $routeParams = scope.$service('$routeParams'),
- firstRouteParams = $routeParams;
-
- $route.when('/foo');
- $route.when('/bar/:barId');
-
- $location.path('/foo').search('a=b');
- scope.$digest();
- expect(scope.$service('$routeParams')).toBe(firstRouteParams);
-
- $location.path('/bar/123').search('x=abc');
- scope.$digest();
- expect(scope.$service('$routeParams')).toBe(firstRouteParams);
- });
+ }));
});
diff --git a/test/service/routeSpec.js b/test/service/routeSpec.js
index 5aba2a1f..26ae17e5 100644
--- a/test/service/routeSpec.js
+++ b/test/service/routeSpec.js
@@ -1,16 +1,7 @@
'use strict';
describe('$route', function() {
- var scope, $route, $location;
-
- beforeEach(function() {
- scope = angular.scope();
- $location = scope.$service('$location');
- $route = scope.$service('$route');
- });
-
-
- it('should route and fire change event', function() {
+ it('should route and fire change event', inject(function($route, $location, $rootScope) {
var log = '',
lastRoute,
nextRoute;
@@ -21,13 +12,13 @@ describe('$route', function() {
$route.when('/Book/:book/Chapter/:chapter', {controller: BookChapter, template: 'Chapter.html'});
$route.when('/Blank');
- scope.$on('$beforeRouteChange', function(event, next, current) {
+ $rootScope.$on('$beforeRouteChange', function(event, next, current) {
log += 'before();';
expect(current).toBe($route.current);
lastRoute = current;
nextRoute = next;
});
- scope.$on('$afterRouteChange', function(event, current, last) {
+ $rootScope.$on('$afterRouteChange', function(event, current, last) {
log += 'after();';
expect(current).toBe($route.current);
expect(lastRoute).toBe(last);
@@ -35,97 +26,98 @@ describe('$route', function() {
});
$location.path('/Book/Moby/Chapter/Intro').search('p=123');
- scope.$digest();
+ $rootScope.$digest();
expect(log).toEqual('before();<init>;after();');
expect($route.current.params).toEqual({book:'Moby', chapter:'Intro', p:'123'});
var lastId = $route.current.scope.$id;
log = '';
$location.path('/Blank').search('ignore');
- scope.$digest();
+ $rootScope.$digest();
expect(log).toEqual('before();after();');
expect($route.current.params).toEqual({ignore:true});
expect($route.current.scope.$id).not.toEqual(lastId);
log = '';
$location.path('/NONE');
- scope.$digest();
+ $rootScope.$digest();
expect(log).toEqual('before();after();');
expect($route.current).toEqual(null);
$route.when('/NONE', {template:'instant update'});
- scope.$digest();
+ $rootScope.$digest();
expect($route.current.template).toEqual('instant update');
- });
+ }));
- it('should match a route that contains special chars in the path', function() {
+ it('should match a route that contains special chars in the path', inject(function($route, $location, $rootScope) {
$route.when('/$test.23/foo(bar)/:baz', {template: 'test.html'});
$location.path('/test');
- scope.$digest();
+ $rootScope.$digest();
expect($route.current).toBeUndefined();
$location.path('/$testX23/foo(bar)/222');
- scope.$digest();
+ $rootScope.$digest();
expect($route.current).toBeUndefined();
$location.path('/$test.23/foo(bar)/222');
- scope.$digest();
+ $rootScope.$digest();
expect($route.current).toBeDefined();
$location.path('/$test.23/foo\\(bar)/222');
- scope.$digest();
+ $rootScope.$digest();
expect($route.current).toBeUndefined();
- });
+ }));
- it('should change route even when only search param changes', function() {
+ it('should change route even when only search param changes', inject(function($route, $location, $rootScope) {
var callback = jasmine.createSpy('onRouteChange');
$route.when('/test', {template: 'test.html'});
- scope.$on('$beforeRouteChange', callback);
+ $rootScope.$on('$beforeRouteChange', callback);
$location.path('/test');
- scope.$digest();
+ $rootScope.$digest();
callback.reset();
$location.search({any: true});
- scope.$digest();
+ $rootScope.$digest();
expect(callback).toHaveBeenCalled();
- });
+ }));
- it('should allow routes to be defined with just templates without controllers', function() {
+ it('should allow routes to be defined with just templates without controllers',
+ inject(function($route, $location, $rootScope) {
var onChangeSpy = jasmine.createSpy('onChange');
$route.when('/foo', {template: 'foo.html'});
- scope.$on('$beforeRouteChange', onChangeSpy);
+ $rootScope.$on('$beforeRouteChange', onChangeSpy);
expect($route.current).toBeUndefined();
expect(onChangeSpy).not.toHaveBeenCalled();
$location.path('/foo');
- scope.$digest();
+ $rootScope.$digest();
expect($route.current.template).toEqual('foo.html');
expect($route.current.controller).toBeUndefined();
expect(onChangeSpy).toHaveBeenCalled();
- });
+ }));
- it('should handle unknown routes with "otherwise" route definition', function() {
+ it('should handle unknown routes with "otherwise" route definition', inject(function($route, $location, $rootScope) {
var onChangeSpy = jasmine.createSpy('onChange');
function NotFoundCtrl() {this.notFoundProp = 'not found!';}
$route.when('/foo', {template: 'foo.html'});
$route.otherwise({template: '404.html', controller: NotFoundCtrl});
- scope.$on('$beforeRouteChange', onChangeSpy);
+ $rootScope.$on('$beforeRouteChange', onChangeSpy);
expect($route.current).toBeUndefined();
expect(onChangeSpy).not.toHaveBeenCalled();
$location.path('/unknownRoute');
- scope.$digest();
+ $rootScope.$digest();
expect($route.current.template).toBe('404.html');
expect($route.current.controller).toBe(NotFoundCtrl);
@@ -134,54 +126,55 @@ describe('$route', function() {
onChangeSpy.reset();
$location.path('/foo');
- scope.$digest();
+ $rootScope.$digest();
expect($route.current.template).toEqual('foo.html');
expect($route.current.controller).toBeUndefined();
expect($route.current.scope.notFoundProp).toBeUndefined();
expect(onChangeSpy).toHaveBeenCalled();
- });
+ }));
- it('should $destroy old routes', function() {
+ it('should $destroy old routes', inject(function($route, $location, $rootScope) {
$route.when('/foo', {template: 'foo.html', controller: function() {this.name = 'FOO';}});
$route.when('/bar', {template: 'bar.html', controller: function() {this.name = 'BAR';}});
$route.when('/baz', {template: 'baz.html'});
- expect(scope.$childHead).toEqual(null);
+ expect($rootScope.$childHead).toEqual(null);
$location.path('/foo');
- scope.$digest();
- expect(scope.$$childHead.$id).toBeTruthy();
- expect(scope.$$childHead.$id).toEqual(scope.$$childTail.$id);
+ $rootScope.$digest();
+ expect($rootScope.$$childHead.$id).toBeTruthy();
+ expect($rootScope.$$childHead.$id).toEqual($rootScope.$$childTail.$id);
$location.path('/bar');
- scope.$digest();
- expect(scope.$$childHead.$id).toBeTruthy();
- expect(scope.$$childHead.$id).toEqual(scope.$$childTail.$id);
+ $rootScope.$digest();
+ expect($rootScope.$$childHead.$id).toBeTruthy();
+ expect($rootScope.$$childHead.$id).toEqual($rootScope.$$childTail.$id);
$location.path('/baz');
- scope.$digest();
- expect(scope.$$childHead.$id).toBeTruthy();
- expect(scope.$$childHead.$id).toEqual(scope.$$childTail.$id);
+ $rootScope.$digest();
+ expect($rootScope.$$childHead.$id).toBeTruthy();
+ expect($rootScope.$$childHead.$id).toEqual($rootScope.$$childTail.$id);
$location.path('/');
- scope.$digest();
- expect(scope.$$childHead).toEqual(null);
- expect(scope.$$childTail).toEqual(null);
- });
+ $rootScope.$digest();
+ expect($rootScope.$$childHead).toEqual(null);
+ expect($rootScope.$$childTail).toEqual(null);
+ }));
- it('should infer arguments in injection', function() {
+ it('should infer arguments in injection', inject(function($route, $location, $rootScope) {
$route.when('/test', {controller: function($route){ this.$route = $route; }});
$location.path('/test');
- scope.$digest();
+ $rootScope.$digest();
expect($route.current.scope.$route).toBe($route);
- });
+ }));
describe('redirection', function() {
- it('should support redirection via redirectTo property by updating $location', function() {
+ it('should support redirection via redirectTo property by updating $location',
+ inject(function($route, $location, $rootScope) {
var onChangeSpy = jasmine.createSpy('onChange');
$route.when('/', {redirectTo: '/foo'});
@@ -189,57 +182,59 @@ describe('$route', function() {
$route.when('/bar', {template: 'bar.html'});
$route.when('/baz', {redirectTo: '/bar'});
$route.otherwise({template: '404.html'});
- scope.$on('$beforeRouteChange', onChangeSpy);
+ $rootScope.$on('$beforeRouteChange', onChangeSpy);
expect($route.current).toBeUndefined();
expect(onChangeSpy).not.toHaveBeenCalled();
$location.path('/');
- scope.$digest();
+ $rootScope.$digest();
expect($location.path()).toBe('/foo');
expect($route.current.template).toBe('foo.html');
expect(onChangeSpy.callCount).toBe(2);
onChangeSpy.reset();
$location.path('/baz');
- scope.$digest();
+ $rootScope.$digest();
expect($location.path()).toBe('/bar');
expect($route.current.template).toBe('bar.html');
expect(onChangeSpy.callCount).toBe(2);
- });
+ }));
- it('should interpolate route vars in the redirected path from original path', function() {
+ it('should interpolate route vars in the redirected path from original path',
+ inject(function($route, $location, $rootScope) {
$route.when('/foo/:id/foo/:subid/:extraId', {redirectTo: '/bar/:id/:subid/23'});
$route.when('/bar/:id/:subid/:subsubid', {template: 'bar.html'});
$location.path('/foo/id1/foo/subid3/gah');
- scope.$digest();
+ $rootScope.$digest();
expect($location.path()).toEqual('/bar/id1/subid3/23');
expect($location.search()).toEqual({extraId: 'gah'});
expect($route.current.template).toEqual('bar.html');
- });
+ }));
- it('should interpolate route vars in the redirected path from original search', function() {
+ it('should interpolate route vars in the redirected path from original search',
+ inject(function($route, $location, $rootScope) {
$route.when('/bar/:id/:subid/:subsubid', {template: 'bar.html'});
$route.when('/foo/:id/:extra', {redirectTo: '/bar/:id/:subid/99'});
$location.path('/foo/id3/eId').search('subid=sid1&appended=true');
- scope.$digest();
+ $rootScope.$digest();
expect($location.path()).toEqual('/bar/id3/sid1/99');
expect($location.search()).toEqual({appended: 'true', extra: 'eId'});
expect($route.current.template).toEqual('bar.html');
- });
+ }));
- it('should allow custom redirectTo function to be used', function() {
+ it('should allow custom redirectTo function to be used', inject(function($route, $location, $rootScope) {
$route.when('/bar/:id/:subid/:subsubid', {template: 'bar.html'});
$route.when('/foo/:id', {redirectTo: customRedirectFn});
$location.path('/foo/id3').search('subid=sid1&appended=true');
- scope.$digest();
+ $rootScope.$digest();
expect($location.path()).toEqual('/custom');
@@ -249,60 +244,61 @@ describe('$route', function() {
expect(search).toEqual($location.search());
return '/custom';
}
- });
+ }));
- it('should replace the url when redirecting', function() {
+ it('should replace the url when redirecting', inject(function($route, $location, $rootScope) {
$route.when('/bar/:id', {template: 'bar.html'});
$route.when('/foo/:id/:extra', {redirectTo: '/bar/:id'});
var replace;
- scope.$watch(function() {
+ $rootScope.$watch(function() {
if (isUndefined(replace)) replace = $location.$$replace;
});
$location.path('/foo/id3/eId');
- scope.$digest();
+ $rootScope.$digest();
expect($location.path()).toEqual('/bar/id3');
expect(replace).toBe(true);
- });
+ }));
});
describe('reloadOnSearch', function() {
- it('should reload a route when reloadOnSearch is enabled and .search() changes', function() {
- var $routeParams = scope.$service('$routeParams'),
+ it('should reload a route when reloadOnSearch is enabled and .search() changes',
+ inject(function($route, $location, $rootScope) {
+ var $routeParams = $rootScope.$service('$routeParams'),
reloaded = jasmine.createSpy('route reload');
$route.when('/foo', {controller: FooCtrl});
- scope.$on('$beforeRouteChange', reloaded);
+ $rootScope.$on('$beforeRouteChange', reloaded);
function FooCtrl() {
reloaded();
}
$location.path('/foo');
- scope.$digest();
+ $rootScope.$digest();
expect(reloaded).toHaveBeenCalled();
expect($routeParams).toEqual({});
reloaded.reset();
// trigger reload
$location.search({foo: 'bar'});
- scope.$digest();
+ $rootScope.$digest();
expect(reloaded).toHaveBeenCalled();
expect($routeParams).toEqual({foo:'bar'});
- });
+ }));
it('should not reload a route when reloadOnSearch is disabled and only .search() changes',
- function() {
+ inject(function($route, $location, $rootScope) {
var reloaded = jasmine.createSpy('route reload'),
routeUpdateEvent = jasmine.createSpy('route reload');
$route.when('/foo', {controller: FooCtrl, reloadOnSearch: false});
- scope.$on('$beforeRouteChange', reloaded);
+ $rootScope.$on('$beforeRouteChange', reloaded);
function FooCtrl() {
reloaded();
@@ -312,25 +308,26 @@ describe('$route', function() {
expect(reloaded).not.toHaveBeenCalled();
$location.path('/foo');
- scope.$digest();
+ $rootScope.$digest();
expect(reloaded).toHaveBeenCalled();
expect(routeUpdateEvent).not.toHaveBeenCalled();
reloaded.reset();
// don't trigger reload
$location.search({foo: 'bar'});
- scope.$digest();
+ $rootScope.$digest();
expect(reloaded).not.toHaveBeenCalled();
expect(routeUpdateEvent).toHaveBeenCalled();
- });
+ }));
- it('should reload reloadOnSearch route when url differs only in route path param', function() {
+ it('should reload reloadOnSearch route when url differs only in route path param',
+ inject(function($route, $location, $rootScope) {
var reloaded = jasmine.createSpy('routeReload'),
onRouteChange = jasmine.createSpy('onRouteChange');
$route.when('/foo/:fooId', {controller: FooCtrl, reloadOnSearch: false});
- scope.$on('$beforeRouteChange', onRouteChange);
+ $rootScope.$on('$beforeRouteChange', onRouteChange);
function FooCtrl() {
reloaded();
@@ -340,27 +337,28 @@ describe('$route', function() {
expect(onRouteChange).not.toHaveBeenCalled();
$location.path('/foo/aaa');
- scope.$digest();
+ $rootScope.$digest();
expect(reloaded).toHaveBeenCalled();
expect(onRouteChange).toHaveBeenCalled();
reloaded.reset();
onRouteChange.reset();
$location.path('/foo/bbb');
- scope.$digest();
+ $rootScope.$digest();
expect(reloaded).toHaveBeenCalled();
expect(onRouteChange).toHaveBeenCalled();
reloaded.reset();
onRouteChange.reset();
$location.search({foo: 'bar'});
- scope.$digest();
+ $rootScope.$digest();
expect(reloaded).not.toHaveBeenCalled();
expect(onRouteChange).not.toHaveBeenCalled();
- });
+ }));
- it('should update params when reloadOnSearch is disabled and .search() changes', function() {
+ it('should update params when reloadOnSearch is disabled and .search() changes',
+ inject(function($route, $location, $rootScope) {
var routeParams = jasmine.createSpy('routeParams');
$route.when('/foo', {controller: FooCtrl});
@@ -377,32 +375,32 @@ describe('$route', function() {
expect(routeParams).not.toHaveBeenCalled();
$location.path('/foo');
- scope.$digest();
+ $rootScope.$digest();
expect(routeParams).toHaveBeenCalledWith({});
routeParams.reset();
// trigger reload
$location.search({foo: 'bar'});
- scope.$digest();
+ $rootScope.$digest();
expect(routeParams).toHaveBeenCalledWith({foo: 'bar'});
routeParams.reset();
$location.path('/bar/123').search({});
- scope.$digest();
+ $rootScope.$digest();
expect(routeParams).toHaveBeenCalledWith({barId: '123'});
routeParams.reset();
// don't trigger reload
$location.search({foo: 'bar'});
- scope.$digest();
+ $rootScope.$digest();
expect(routeParams).toHaveBeenCalledWith({barId: '123', foo: 'bar'});
- });
+ }));
describe('reload', function() {
- it('should reload even if reloadOnSearch is false', function() {
- var $routeParams = scope.$service('$routeParams'),
+ it('should reload even if reloadOnSearch is false', inject(function($route, $location, $rootScope) {
+ var $routeParams = $rootScope.$service('$routeParams'),
count = 0;
$route.when('/bar/:barId', {controller: FooCtrl, reloadOnSearch: false});
@@ -410,20 +408,20 @@ describe('$route', function() {
function FooCtrl() { count ++; }
$location.path('/bar/123');
- scope.$digest();
+ $rootScope.$digest();
expect($routeParams).toEqual({barId:'123'});
expect(count).toEqual(1);
$location.path('/bar/123').search('a=b');
- scope.$digest();
+ $rootScope.$digest();
expect($routeParams).toEqual({barId:'123', a:'b'});
expect(count).toEqual(1);
$route.reload();
- scope.$digest();
+ $rootScope.$digest();
expect($routeParams).toEqual({barId:'123', a:'b'});
expect(count).toEqual(2);
- });
+ }));
});
});
});
diff --git a/test/service/scopeSpec.js b/test/service/scopeSpec.js
index d3f58918..2cd2f635 100644
--- a/test/service/scopeSpec.js
+++ b/test/service/scopeSpec.js
@@ -1,70 +1,66 @@
'use strict';
describe('Scope', function() {
- var root = null, mockHandler = null;
- beforeEach(function() {
- root = createScope(angular.service, {
- '$exceptionHandler': $exceptionHandlerMockFactory()
- });
- mockHandler = root.$service('$exceptionHandler');
- });
+ beforeEach(inject(function(service) {
+ service('$exceptionHandler', $exceptionHandlerMockFactory);
+ }));
describe('$root', function() {
- it('should point to itself', function() {
- expect(root.$root).toEqual(root);
- expect(root.hasOwnProperty('$root')).toBeTruthy();
- });
+ it('should point to itself', inject(function($rootScope) {
+ expect($rootScope.$root).toEqual($rootScope);
+ expect($rootScope.hasOwnProperty('$root')).toBeTruthy();
+ }));
- it('should not have $root on children, but should inherit', function() {
- var child = root.$new();
- expect(child.$root).toEqual(root);
+ it('should not have $root on children, but should inherit', inject(function($rootScope) {
+ var child = $rootScope.$new();
+ expect(child.$root).toEqual($rootScope);
expect(child.hasOwnProperty('$root')).toBeFalsy();
- });
+ }));
});
describe('$parent', function() {
- it('should point to itself in root', function() {
- expect(root.$root).toEqual(root);
- });
+ it('should point to itself in root', inject(function($rootScope) {
+ expect($rootScope.$root).toEqual($rootScope);
+ }));
- it('should point to parent', function() {
- var child = root.$new();
- expect(root.$parent).toEqual(null);
- expect(child.$parent).toEqual(root);
+ it('should point to parent', inject(function($rootScope) {
+ var child = $rootScope.$new();
+ expect($rootScope.$parent).toEqual(null);
+ expect(child.$parent).toEqual($rootScope);
expect(child.$new().$parent).toEqual(child);
- });
+ }));
});
describe('$id', function() {
- it('should have a unique id', function() {
- expect(root.$id < root.$new().$id).toBeTruthy();
- });
+ it('should have a unique id', inject(function($rootScope) {
+ expect($rootScope.$id < $rootScope.$new().$id).toBeTruthy();
+ }));
});
describe('this', function() {
- it('should have a \'this\'', function() {
- expect(root['this']).toEqual(root);
- });
+ it('should have a \'this\'', inject(function($rootScope) {
+ expect($rootScope['this']).toEqual($rootScope);
+ }));
});
describe('$new()', function() {
- it('should create a child scope', function() {
- var child = root.$new();
- root.a = 123;
+ it('should create a child scope', inject(function($rootScope) {
+ var child = $rootScope.$new();
+ $rootScope.a = 123;
expect(child.a).toEqual(123);
- });
+ }));
- it('should instantiate controller and bind functions', function() {
+ it('should instantiate controller and bind functions', inject(function($rootScope) {
function Cntl($browser, name){
this.$browser = $browser;
this.callCount = 0;
@@ -79,10 +75,10 @@ describe('Scope', function() {
}
};
- var cntl = root.$new(Cntl, ['misko']);
+ var cntl = $rootScope.$new(Cntl, ['misko']);
- expect(root.$browser).toBeUndefined();
- expect(root.myFn).toBeUndefined();
+ expect($rootScope.$browser).toBeUndefined();
+ expect($rootScope.myFn).toBeUndefined();
expect(cntl.$browser).toBeDefined();
expect(cntl.name).toEqual('misko');
@@ -90,96 +86,89 @@ describe('Scope', function() {
cntl.myFn();
cntl.$new().myFn();
expect(cntl.callCount).toEqual(2);
- });
- });
-
-
- describe('$service', function() {
- it('should have it on root', function() {
- expect(root.hasOwnProperty('$service')).toBeTruthy();
- });
+ }));
});
describe('$watch/$digest', function() {
- it('should watch and fire on simple property change', function() {
+ it('should watch and fire on simple property change', inject(function($rootScope) {
var spy = jasmine.createSpy();
- root.$watch('name', spy);
- root.$digest();
+ $rootScope.$watch('name', spy);
+ $rootScope.$digest();
spy.reset();
expect(spy).not.wasCalled();
- root.$digest();
+ $rootScope.$digest();
expect(spy).not.wasCalled();
- root.name = 'misko';
- root.$digest();
- expect(spy).wasCalledWith(root, 'misko', undefined);
- });
+ $rootScope.name = 'misko';
+ $rootScope.$digest();
+ expect(spy).wasCalledWith($rootScope, 'misko', undefined);
+ }));
- it('should watch and fire on expression change', function() {
+ it('should watch and fire on expression change', inject(function($rootScope) {
var spy = jasmine.createSpy();
- root.$watch('name.first', spy);
- root.$digest();
+ $rootScope.$watch('name.first', spy);
+ $rootScope.$digest();
spy.reset();
- root.name = {};
+ $rootScope.name = {};
expect(spy).not.wasCalled();
- root.$digest();
+ $rootScope.$digest();
expect(spy).not.wasCalled();
- root.name.first = 'misko';
- root.$digest();
+ $rootScope.name.first = 'misko';
+ $rootScope.$digest();
expect(spy).wasCalled();
- });
+ }));
- it('should delegate exceptions', function() {
- root.$watch('a', function() {throw new Error('abc');});
- root.a = 1;
- root.$digest();
- expect(mockHandler.errors[0].message).toEqual('abc');
+ it('should delegate exceptions', inject(function($rootScope, $exceptionHandler) {
+ $rootScope.$watch('a', function() {throw new Error('abc');});
+ $rootScope.a = 1;
+ $rootScope.$digest();
+ expect($exceptionHandler.errors[0].message).toEqual('abc');
$logMock.error.logs.length = 0;
- });
+ }));
- it('should fire watches in order of addition', function() {
+ it('should fire watches in order of addition', inject(function($rootScope) {
// this is not an external guarantee, just our own sanity
var log = '';
- root.$watch('a', function() { log += 'a'; });
- root.$watch('b', function() { log += 'b'; });
- root.$watch('c', function() { log += 'c'; });
- root.a = root.b = root.c = 1;
- root.$digest();
+ $rootScope.$watch('a', function() { log += 'a'; });
+ $rootScope.$watch('b', function() { log += 'b'; });
+ $rootScope.$watch('c', function() { log += 'c'; });
+ $rootScope.a = $rootScope.b = $rootScope.c = 1;
+ $rootScope.$digest();
expect(log).toEqual('abc');
- });
+ }));
- it('should call child $watchers in addition order', function() {
+ it('should call child $watchers in addition order', inject(function($rootScope) {
// this is not an external guarantee, just our own sanity
var log = '';
- var childA = root.$new();
- var childB = root.$new();
- var childC = root.$new();
+ var childA = $rootScope.$new();
+ var childB = $rootScope.$new();
+ var childC = $rootScope.$new();
childA.$watch('a', function() { log += 'a'; });
childB.$watch('b', function() { log += 'b'; });
childC.$watch('c', function() { log += 'c'; });
childA.a = childB.b = childC.c = 1;
- root.$digest();
+ $rootScope.$digest();
expect(log).toEqual('abc');
- });
+ }));
- it('should allow $digest on a child scope with and without a right sibling', function() {
+ it('should allow $digest on a child scope with and without a right sibling', inject(function($rootScope) {
// tests a traversal edge case which we originally missed
var log = '',
- childA = root.$new(),
- childB = root.$new();
+ childA = $rootScope.$new(),
+ childB = $rootScope.$new();
- root.$watch(function() { log += 'r'; });
+ $rootScope.$watch(function() { log += 'r'; });
childA.$watch(function() { log += 'a'; });
childB.$watch(function() { log += 'b'; });
// init
- root.$digest();
+ $rootScope.$digest();
expect(log).toBe('rabrab');
log = '';
@@ -189,114 +178,114 @@ describe('Scope', function() {
log = '';
childB.$digest();
expect(log).toBe('b');
- });
+ }));
- it('should repeat watch cycle while model changes are identified', function() {
+ it('should repeat watch cycle while model changes are identified', inject(function($rootScope) {
var log = '';
- root.$watch('c', function(self, v){self.d = v; log+='c'; });
- root.$watch('b', function(self, v){self.c = v; log+='b'; });
- root.$watch('a', function(self, v){self.b = v; log+='a'; });
- root.$digest();
+ $rootScope.$watch('c', function(self, v){self.d = v; log+='c'; });
+ $rootScope.$watch('b', function(self, v){self.c = v; log+='b'; });
+ $rootScope.$watch('a', function(self, v){self.b = v; log+='a'; });
+ $rootScope.$digest();
log = '';
- root.a = 1;
- root.$digest();
- expect(root.b).toEqual(1);
- expect(root.c).toEqual(1);
- expect(root.d).toEqual(1);
+ $rootScope.a = 1;
+ $rootScope.$digest();
+ expect($rootScope.b).toEqual(1);
+ expect($rootScope.c).toEqual(1);
+ expect($rootScope.d).toEqual(1);
expect(log).toEqual('abc');
- });
+ }));
- it('should repeat watch cycle from the root elemnt', function() {
+ it('should repeat watch cycle from the root elemnt', inject(function($rootScope) {
var log = '';
- var child = root.$new();
- root.$watch(function() { log += 'a'; });
+ var child = $rootScope.$new();
+ $rootScope.$watch(function() { log += 'a'; });
child.$watch(function() { log += 'b'; });
- root.$digest();
+ $rootScope.$digest();
expect(log).toEqual('abab');
- });
+ }));
- it('should prevent infinite recursion and print watcher expression', function() {
- root.$watch('a', function(self){self.b++;});
- root.$watch('b', function(self){self.a++;});
- root.a = root.b = 0;
+ it('should prevent infinite recursion and print watcher expression',inject(function($rootScope) {
+ $rootScope.$watch('a', function(self){self.b++;});
+ $rootScope.$watch('b', function(self){self.a++;});
+ $rootScope.a = $rootScope.b = 0;
expect(function() {
- root.$digest();
+ $rootScope.$digest();
}).toThrow('100 $digest() iterations reached. Aborting!\n'+
'Watchers fired in the last 5 iterations: ' +
'[["a","b"],["a","b"],["a","b"],["a","b"],["a","b"]]');
- });
+ }));
it('should prevent infinite recurcion and print print watcher function name or body',
- function() {
- root.$watch(function watcherA() {return root.a;}, function(self){self.b++;});
- root.$watch(function() {return root.b;}, function(self){self.a++;});
- root.a = root.b = 0;
+ inject(function($rootScope) {
+ $rootScope.$watch(function watcherA() {return $rootScope.a;}, function(self){self.b++;});
+ $rootScope.$watch(function() {return $rootScope.b;}, function(self){self.a++;});
+ $rootScope.a = $rootScope.b = 0;
try {
- root.$digest();
+ $rootScope.$digest();
throw Error('Should have thrown exception');
} catch(e) {
expect(e.message.match(/"fn: (watcherA|function)/g).length).toBe(10);
}
- });
+ }));
- it('should not fire upon $watch registration on initial $digest', function() {
+ it('should not fire upon $watch registration on initial $digest', inject(function($rootScope) {
var log = '';
- root.a = 1;
- root.$watch('a', function() { log += 'a'; });
- root.$watch('b', function() { log += 'b'; });
- root.$digest();
+ $rootScope.a = 1;
+ $rootScope.$watch('a', function() { log += 'a'; });
+ $rootScope.$watch('b', function() { log += 'b'; });
+ $rootScope.$digest();
log = '';
- root.$digest();
+ $rootScope.$digest();
expect(log).toEqual('');
- });
+ }));
- it('should watch objects', function() {
+ it('should watch objects', inject(function($rootScope) {
var log = '';
- root.a = [];
- root.b = {};
- root.$watch('a', function(scope, value){
+ $rootScope.a = [];
+ $rootScope.b = {};
+ $rootScope.$watch('a', function(scope, value){
log +='.';
- expect(value).toBe(root.a);
+ expect(value).toBe($rootScope.a);
});
- root.$watch('b', function(scope, value){
+ $rootScope.$watch('b', function(scope, value){
log +='!';
- expect(value).toBe(root.b);
+ expect(value).toBe($rootScope.b);
});
- root.$digest();
+ $rootScope.$digest();
log = '';
- root.a.push({});
- root.b.name = '';
+ $rootScope.a.push({});
+ $rootScope.b.name = '';
- root.$digest();
+ $rootScope.$digest();
expect(log).toEqual('.!');
- });
+ }));
- it('should prevent recursion', function() {
+ it('should prevent recursion', inject(function($rootScope) {
var callCount = 0;
- root.$watch('name', function() {
+ $rootScope.$watch('name', function() {
expect(function() {
- root.$digest();
+ $rootScope.$digest();
}).toThrow('$digest already in progress');
callCount++;
});
- root.name = 'a';
- root.$digest();
+ $rootScope.name = 'a';
+ $rootScope.$digest();
expect(callCount).toEqual(1);
- });
+ }));
- it('should return a function that allows listeners to be unregistered', function() {
- var root = angular.scope(),
+ it('should return a function that allows listeners to be unregistered', inject(function($rootScope) {
+ var root = angular.injector()('$rootScope'),
listener = jasmine.createSpy('watch listener'),
listenerRemove;
@@ -315,166 +304,162 @@ describe('Scope', function() {
listenerRemove();
root.$digest(); //trigger
expect(listener).not.toHaveBeenCalled();
- });
+ }));
});
describe('$destroy', function() {
var first = null, middle = null, last = null, log = null;
- beforeEach(function() {
+ beforeEach(inject(function($rootScope) {
log = '';
- first = root.$new();
- middle = root.$new();
- last = root.$new();
+ first = $rootScope.$new();
+ middle = $rootScope.$new();
+ last = $rootScope.$new();
first.$watch(function() { log += '1';});
middle.$watch(function() { log += '2';});
last.$watch(function() { log += '3';});
- root.$digest();
+ $rootScope.$digest();
log = '';
- });
+ }));
- it('should ignore remove on root', function() {
- root.$destroy();
- root.$digest();
+ it('should ignore remove on root', inject(function($rootScope) {
+ $rootScope.$destroy();
+ $rootScope.$digest();
expect(log).toEqual('123');
- });
+ }));
- it('should remove first', function() {
+ it('should remove first', inject(function($rootScope) {
first.$destroy();
- root.$digest();
+ $rootScope.$digest();
expect(log).toEqual('23');
- });
+ }));
- it('should remove middle', function() {
+ it('should remove middle', inject(function($rootScope) {
middle.$destroy();
- root.$digest();
+ $rootScope.$digest();
expect(log).toEqual('13');
- });
+ }));
- it('should remove last', function() {
+ it('should remove last', inject(function($rootScope) {
last.$destroy();
- root.$digest();
+ $rootScope.$digest();
expect(log).toEqual('12');
- });
+ }));
- it('should fire a $destroy event', function() {
+ it('should fire a $destroy event', inject(function($rootScope) {
var destructedScopes = [];
middle.$on('$destroy', function(event) {
destructedScopes.push(event.currentScope);
});
middle.$destroy();
expect(destructedScopes).toEqual([middle]);
- });
+ }));
});
describe('$eval', function() {
- it('should eval an expression', function() {
- expect(root.$eval('a=1')).toEqual(1);
- expect(root.a).toEqual(1);
+ it('should eval an expression', inject(function($rootScope) {
+ expect($rootScope.$eval('a=1')).toEqual(1);
+ expect($rootScope.a).toEqual(1);
- root.$eval(function(self){self.b=2;});
- expect(root.b).toEqual(2);
- });
+ $rootScope.$eval(function(self){self.b=2;});
+ expect($rootScope.b).toEqual(2);
+ }));
});
describe('$evalAsync', function() {
- it('should run callback before $watch', function() {
+ it('should run callback before $watch', inject(function($rootScope) {
var log = '';
- var child = root.$new();
- root.$evalAsync(function(scope){ log += 'parent.async;'; });
- root.$watch('value', function() { log += 'parent.$digest;'; });
+ var child = $rootScope.$new();
+ $rootScope.$evalAsync(function(scope){ log += 'parent.async;'; });
+ $rootScope.$watch('value', function() { log += 'parent.$digest;'; });
child.$evalAsync(function(scope){ log += 'child.async;'; });
child.$watch('value', function() { log += 'child.$digest;'; });
- root.$digest();
+ $rootScope.$digest();
expect(log).toEqual('parent.async;parent.$digest;child.async;child.$digest;');
- });
-
- it('should cause a $digest rerun', function() {
- root.log = '';
- root.value = 0;
- root.$watch('value', 'log = log + ".";');
- root.$watch('init', function() {
- root.$evalAsync('value = 123; log = log + "=" ');
- expect(root.value).toEqual(0);
+ }));
+
+ it('should cause a $digest rerun', inject(function($rootScope) {
+ $rootScope.log = '';
+ $rootScope.value = 0;
+ $rootScope.$watch('value', 'log = log + ".";');
+ $rootScope.$watch('init', function() {
+ $rootScope.$evalAsync('value = 123; log = log + "=" ');
+ expect($rootScope.value).toEqual(0);
});
- root.$digest();
- expect(root.log).toEqual('.=.');
- });
-
- it('should run async in the same order as added', function() {
- root.log = '';
- root.$evalAsync("log = log + 1");
- root.$evalAsync("log = log + 2");
- root.$digest();
- expect(root.log).toBe('12');
- });
+ $rootScope.$digest();
+ expect($rootScope.log).toEqual('.=.');
+ }));
+
+ it('should run async in the same order as added', inject(function($rootScope) {
+ $rootScope.log = '';
+ $rootScope.$evalAsync("log = log + 1");
+ $rootScope.$evalAsync("log = log + 2");
+ $rootScope.$digest();
+ expect($rootScope.log).toBe('12');
+ }));
});
describe('$apply', function() {
- it('should apply expression with full lifecycle', function() {
+ it('should apply expression with full lifecycle', inject(function($rootScope) {
var log = '';
- var child = root.$new();
- root.$watch('a', function(scope, a){ log += '1'; });
+ var child = $rootScope.$new();
+ $rootScope.$watch('a', function(scope, a){ log += '1'; });
child.$apply('$parent.a=0');
expect(log).toEqual('1');
- });
+ }));
- it('should catch exceptions', function() {
+ it('should catch exceptions', inject(function($rootScope, $exceptionHandler) {
var log = '';
- var child = root.$new();
- root.$watch('a', function(scope, a){ log += '1'; });
- root.a = 0;
+ var child = $rootScope.$new();
+ $rootScope.$watch('a', function(scope, a){ log += '1'; });
+ $rootScope.a = 0;
child.$apply(function() { throw new Error('MyError'); });
expect(log).toEqual('1');
- expect(mockHandler.errors[0].message).toEqual('MyError');
+ expect($exceptionHandler.errors[0].message).toEqual('MyError');
$logMock.error.logs.shift();
- });
+ }));
describe('exceptions', function() {
- var $exceptionHandler, log;
- beforeEach(function() {
+ var log;
+ beforeEach(inject(function($rootScope) {
log = '';
- $exceptionHandler = jasmine.createSpy('$exceptionHandler');
- root.$service = function(name) {
- return {$exceptionHandler:$exceptionHandler}[name];
- };
- root.$watch(function() { log += '$digest;'; });
- root.$digest();
+ $rootScope.$watch(function() { log += '$digest;'; });
+ $rootScope.$digest();
log = '';
- });
+ }));
- it('should execute and return value and update', function() {
- root.name = 'abc';
- expect(root.$apply(function(scope){
+ it('should execute and return value and update', inject(function($rootScope, $exceptionHandler) {
+ $rootScope.name = 'abc';
+ expect($rootScope.$apply(function(scope){
return scope.name;
})).toEqual('abc');
expect(log).toEqual('$digest;');
- expect($exceptionHandler).not.wasCalled();
- });
+ expect($exceptionHandler.errors).toEqual([]);
+ }));
- it('should catch exception and update', function() {
+ it('should catch exception and update', inject(function($rootScope, $exceptionHandler) {
var error = new Error('MyError');
- root.$apply(function() { throw error; });
+ $rootScope.$apply(function() { throw error; });
expect(log).toEqual('$digest;');
- expect($exceptionHandler).wasCalledWith(error);
- });
+ expect($exceptionHandler.errors).toEqual([error]);
+ }));
});
});
@@ -483,9 +468,9 @@ describe('Scope', function() {
describe('$on', function() {
- it('should add listener for both $emit and $broadcast events', function() {
+ it('should add listener for both $emit and $broadcast events', inject(function($rootScope) {
var log = '',
- root = angular.scope(),
+ root = angular.injector()('$rootScope'),
child = root.$new();
function eventFn() {
@@ -500,12 +485,12 @@ describe('Scope', function() {
child.$broadcast('abc');
expect(log).toEqual('XX');
- });
+ }));
- it('should return a function that deregisters the listener', function() {
+ it('should return a function that deregisters the listener', inject(function($rootScope) {
var log = '',
- root = angular.scope(),
+ root = angular.injector()('$rootScope'),
child = root.$new(),
listenerRemove;
@@ -526,7 +511,7 @@ describe('Scope', function() {
child.$emit('abc');
child.$broadcast('abc');
expect(log).toEqual('');
- });
+ }));
});
@@ -537,55 +522,56 @@ describe('Scope', function() {
log += event.currentScope.id + '>';
}
- beforeEach(function() {
+ beforeEach(inject(function($rootScope) {
log = '';
- child = root.$new();
+ child = $rootScope.$new();
grandChild = child.$new();
greatGrandChild = grandChild.$new();
- root.id = 0;
+ $rootScope.id = 0;
child.id = 1;
grandChild.id = 2;
greatGrandChild.id = 3;
- root.$on('myEvent', logger);
+ $rootScope.$on('myEvent', logger);
child.$on('myEvent', logger);
grandChild.$on('myEvent', logger);
greatGrandChild.$on('myEvent', logger);
- });
+ }));
- it('should bubble event up to the root scope', function() {
+ it('should bubble event up to the root scope', inject(function($rootScope) {
grandChild.$emit('myEvent');
expect(log).toEqual('2>1>0>');
- });
+ }));
- it('should dispatch exceptions to the $exceptionHandler', function() {
+ it('should dispatch exceptions to the $exceptionHandler',
+ inject(function($rootScope, $exceptionHandler) {
child.$on('myEvent', function() { throw 'bubbleException'; });
grandChild.$emit('myEvent');
expect(log).toEqual('2>1>0>');
- expect(mockHandler.errors).toEqual(['bubbleException']);
- });
+ expect($exceptionHandler.errors).toEqual(['bubbleException']);
+ }));
- it('should allow cancelation of event propagation', function() {
+ it('should allow cancelation of event propagation', inject(function($rootScope) {
child.$on('myEvent', function(event){ event.cancel(); });
grandChild.$emit('myEvent');
expect(log).toEqual('2>1>');
- });
+ }));
- it('should forward method arguments', function() {
+ it('should forward method arguments', inject(function($rootScope) {
child.$on('abc', function(event, arg1, arg2){
expect(event.name).toBe('abc');
expect(arg1).toBe('arg1');
expect(arg2).toBe('arg2');
});
child.$emit('abc', 'arg1', 'arg2');
- });
+ }));
describe('event object', function() {
- it('should have methods/properties', function() {
+ it('should have methods/properties', inject(function($rootScope) {
var event;
child.$on('myEvent', function(e){
expect(e.targetScope).toBe(grandChild);
@@ -595,7 +581,7 @@ describe('Scope', function() {
});
grandChild.$emit('myEvent');
expect(event).toBeDefined();
- });
+ }));
});
});
@@ -609,18 +595,18 @@ describe('Scope', function() {
log += event.currentScope.id + '>';
}
- beforeEach(function() {
+ beforeEach(inject(function($rootScope) {
log = '';
- child1 = root.$new();
- child2 = root.$new();
- child3 = root.$new();
+ child1 = $rootScope.$new();
+ child2 = $rootScope.$new();
+ child3 = $rootScope.$new();
grandChild11 = child1.$new();
grandChild21 = child2.$new();
grandChild22 = child2.$new();
grandChild23 = child2.$new();
greatGrandChild211 = grandChild21.$new();
- root.id = 0;
+ $rootScope.id = 0;
child1.id = 1;
child2.id = 2;
child3.id = 3;
@@ -630,7 +616,7 @@ describe('Scope', function() {
grandChild23.id = 23;
greatGrandChild211.id = 211;
- root.$on('myEvent', logger);
+ $rootScope.$on('myEvent', logger);
child1.$on('myEvent', logger);
child2.$on('myEvent', logger);
child3.$on('myEvent', logger);
@@ -647,43 +633,43 @@ describe('Scope', function() {
// 11 21 22 23
// |
// 211
- });
+ }));
- it('should broadcast an event from the root scope', function() {
- root.$broadcast('myEvent');
+ it('should broadcast an event from the root scope', inject(function($rootScope) {
+ $rootScope.$broadcast('myEvent');
expect(log).toBe('0>1>11>2>21>211>22>23>3>');
- });
+ }));
- it('should broadcast an event from a child scope', function() {
+ it('should broadcast an event from a child scope', inject(function($rootScope) {
child2.$broadcast('myEvent');
expect(log).toBe('2>21>211>22>23>');
- });
+ }));
- it('should broadcast an event from a leaf scope with a sibling', function() {
+ it('should broadcast an event from a leaf scope with a sibling', inject(function($rootScope) {
grandChild22.$broadcast('myEvent');
expect(log).toBe('22>');
- });
+ }));
- it('should broadcast an event from a leaf scope without a sibling', function() {
+ it('should broadcast an event from a leaf scope without a sibling', inject(function($rootScope) {
grandChild23.$broadcast('myEvent');
expect(log).toBe('23>');
- });
+ }));
- it('should not not fire any listeners for other events', function() {
- root.$broadcast('fooEvent');
+ it('should not not fire any listeners for other events', inject(function($rootScope) {
+ $rootScope.$broadcast('fooEvent');
expect(log).toBe('');
- });
+ }));
});
describe('listener', function() {
- it('should receive event object', function() {
- var scope = angular.scope(),
+ it('should receive event object', inject(function($rootScope) {
+ var scope = angular.injector()('$rootScope'),
child = scope.$new(),
event;
@@ -695,11 +681,11 @@ describe('Scope', function() {
expect(event.name).toBe('fooEvent');
expect(event.targetScope).toBe(scope);
expect(event.currentScope).toBe(child);
- });
+ }));
- it('should support passing messages as varargs', function() {
- var scope = angular.scope(),
+ it('should support passing messages as varargs', inject(function($rootScope) {
+ var scope = angular.injector()('$rootScope'),
child = scope.$new(),
args;
@@ -710,7 +696,7 @@ describe('Scope', function() {
expect(args.length).toBe(5);
expect(sliceArgs(args, 1)).toEqual(['do', 're', 'me', 'fa']);
- });
+ }));
});
});
});
diff --git a/test/service/windowSpec.js b/test/service/windowSpec.js
index c539e285..3b847146 100644
--- a/test/service/windowSpec.js
+++ b/test/service/windowSpec.js
@@ -1,19 +1,7 @@
'use strict';
describe('$window', function() {
- var scope;
-
- beforeEach(function() {
- scope = angular.scope();
- });
-
-
- afterEach(function() {
- dealoc(scope);
- });
-
-
- it("should inject $window", function() {
- expect(scope.$service('$window')).toBe(window);
- });
+ it("should inject $window", inject(function($window) {
+ expect($window).toBe(window);
+ }));
});
diff --git a/test/service/xhr.bulkSpec.js b/test/service/xhr.bulkSpec.js
index 6b99fbba..6f273f64 100644
--- a/test/service/xhr.bulkSpec.js
+++ b/test/service/xhr.bulkSpec.js
@@ -1,24 +1,16 @@
'use strict';
describe('$xhr.bulk', function() {
- var scope, $browser, $browserXhr, $log, $xhrBulk, $xhrError, log;
+ var log;
- beforeEach(function() {
- scope = angular.scope(angular.service, {
- '$xhr.error': $xhrError = jasmine.createSpy('$xhr.error'),
- '$log': $log = {}
+ beforeEach(inject(function(service) {
+ service('$xhr.error', function(){
+ return jasmine.createSpy('$xhr.error');
});
- $browser = scope.$service('$browser');
- $browserXhr = $browser.xhr;
- $xhrBulk = scope.$service('$xhr.bulk');
- $log = scope.$service('$log');
+ service.alias('$xhr.error', '$xhrError');
+ service.alias('$xhr.bulk', '$xhrBulk');
log = '';
- });
-
-
- afterEach(function() {
- dealoc(scope);
- });
+ }));
function callback(code, response) {
@@ -27,12 +19,12 @@ describe('$xhr.bulk', function() {
}
- it('should collect requests', function() {
+ it('should collect requests', inject(function($browser, $xhrBulk) {
$xhrBulk.urls["/"] = {match:/.*/};
$xhrBulk('GET', '/req1', null, callback);
$xhrBulk('POST', '/req2', {post:'data'}, callback);
- $browserXhr.expectPOST('/', {
+ $browser.xhr.expectPOST('/', {
requests:[{method:'GET', url:'/req1', data: null},
{method:'POST', url:'/req2', data:{post:'data'} }]
}).respond([
@@ -40,17 +32,18 @@ describe('$xhr.bulk', function() {
{status:200, response:'second'}
]);
$xhrBulk.flush(function() { log += 'DONE';});
- $browserXhr.flush();
+ $browser.xhr.flush();
expect(log).toEqual('"first";"second";DONE');
- });
+ }));
- it('should handle non 200 status code by forwarding to error handler', function() {
+ it('should handle non 200 status code by forwarding to error handler',
+ inject(function($browser, $xhrBulk, $xhrError) {
$xhrBulk.urls['/'] = {match:/.*/};
$xhrBulk('GET', '/req1', null, callback);
$xhrBulk('POST', '/req2', {post:'data'}, callback);
- $browserXhr.expectPOST('/', {
+ $browser.xhr.expectPOST('/', {
requests:[{method:'GET', url:'/req1', data: null},
{method:'POST', url:'/req2', data:{post:'data'} }]
}).respond([
@@ -58,7 +51,7 @@ describe('$xhr.bulk', function() {
{status:200, response:'second'}
]);
$xhrBulk.flush(function() { log += 'DONE';});
- $browserXhr.flush();
+ $browser.xhr.flush();
expect($xhrError).toHaveBeenCalled();
var cb = $xhrError.mostRecentCall.args[0].success;
@@ -68,22 +61,23 @@ describe('$xhr.bulk', function() {
{status: 404, response: 'NotFound'});
expect(log).toEqual('"second";DONE');
- });
+ }));
- it('should handle non 200 status code by calling error callback if provided', function() {
+ it('should handle non 200 status code by calling error callback if provided',
+ inject(function($browser, $xhrBulk, $xhrError) {
var callback = jasmine.createSpy('error');
$xhrBulk.urls['/'] = {match: /.*/};
$xhrBulk('GET', '/req1', null, noop, callback);
- $browserXhr.expectPOST('/', {
+ $browser.xhr.expectPOST('/', {
requests:[{method: 'GET', url: '/req1', data: null}]
}).respond([{status: 404, response: 'NotFound'}]);
$xhrBulk.flush();
- $browserXhr.flush();
+ $browser.xhr.flush();
expect($xhrError).not.toHaveBeenCalled();
expect(callback).toHaveBeenCalledWith(404, 'NotFound');
- });
+ }));
});
diff --git a/test/service/xhr.cacheSpec.js b/test/service/xhr.cacheSpec.js
index 0c77e629..328dfe3a 100644
--- a/test/service/xhr.cacheSpec.js
+++ b/test/service/xhr.cacheSpec.js
@@ -1,20 +1,17 @@
'use strict';
describe('$xhr.cache', function() {
- var scope, $browser, $browserXhr, $xhrErr, cache, log;
-
- beforeEach(function() {
- scope = angular.scope(angularService, {'$xhr.error': $xhrErr = jasmine.createSpy('$xhr.error')});
- $browser = scope.$service('$browser');
- $browserXhr = $browser.xhr;
- cache = scope.$service('$xhr.cache');
+ var log;
+
+ beforeEach(inject(function(service) {
+ service('$xhr.error', function(){
+ return jasmine.createSpy('$xhr.error');
+ });
+ service.alias('$xhr.cache', '$xhrCache');
+ service.alias('$xhr.bulk', '$xhrBulk');
+ service.alias('$xhr.error', '$xhrError');
log = '';
- });
-
-
- afterEach(function() {
- dealoc(scope);
- });
+ }));
function callback(code, response) {
@@ -23,156 +20,158 @@ describe('$xhr.cache', function() {
}
- it('should cache requests', function() {
- $browserXhr.expectGET('/url').respond('first');
- cache('GET', '/url', null, callback);
- $browserXhr.flush();
+ it('should cache requests', inject(function($browser, $xhrCache) {
+ $browser.xhr.expectGET('/url').respond('first');
+ $xhrCache('GET', '/url', null, callback);
+ $browser.xhr.flush();
- $browserXhr.expectGET('/url').respond('ERROR');
- cache('GET', '/url', null, callback);
+ $browser.xhr.expectGET('/url').respond('ERROR');
+ $xhrCache('GET', '/url', null, callback);
$browser.defer.flush();
expect(log).toEqual('"first";"first";');
- cache('GET', '/url', null, callback, false);
+ $xhrCache('GET', '/url', null, callback, false);
$browser.defer.flush();
expect(log).toEqual('"first";"first";"first";');
- });
+ }));
- it('should first return cache request, then return server request', function() {
- $browserXhr.expectGET('/url').respond('first');
- cache('GET', '/url', null, callback, true);
- $browserXhr.flush();
+ it('should first return cache request, then return server request', inject(function($browser, $xhrCache) {
+ $browser.xhr.expectGET('/url').respond('first');
+ $xhrCache('GET', '/url', null, callback, true);
+ $browser.xhr.flush();
- $browserXhr.expectGET('/url').respond('ERROR');
- cache('GET', '/url', null, callback, true);
+ $browser.xhr.expectGET('/url').respond('ERROR');
+ $xhrCache('GET', '/url', null, callback, true);
$browser.defer.flush();
expect(log).toEqual('"first";"first";');
- $browserXhr.flush();
+ $browser.xhr.flush();
expect(log).toEqual('"first";"first";"ERROR";');
- });
+ }));
- it('should serve requests from cache', function() {
- cache.data.url = {value:'123'};
- cache('GET', 'url', null, callback);
+ it('should serve requests from cache', inject(function($browser, $xhrCache) {
+ $xhrCache.data.url = {value:'123'};
+ $xhrCache('GET', 'url', null, callback);
$browser.defer.flush();
expect(log).toEqual('"123";');
- cache('GET', 'url', null, callback, false);
+ $xhrCache('GET', 'url', null, callback, false);
$browser.defer.flush();
expect(log).toEqual('"123";"123";');
- });
+ }));
- it('should keep track of in flight requests and request only once', function() {
- scope.$service('$xhr.bulk').urls['/bulk'] = {
+ it('should keep track of in flight requests and request only once', inject(function($browser, $xhrCache, $xhrBulk) {
+ $xhrBulk.urls['/bulk'] = {
match:function(url){
return url == '/url';
}
};
- $browserXhr.expectPOST('/bulk', {
+ $browser.xhr.expectPOST('/bulk', {
requests:[{method:'GET', url:'/url', data: null}]
}).respond([
{status:200, response:'123'}
]);
- cache('GET', '/url', null, callback);
- cache('GET', '/url', null, callback);
- cache.delegate.flush();
- $browserXhr.flush();
+ $xhrCache('GET', '/url', null, callback);
+ $xhrCache('GET', '/url', null, callback);
+ $xhrCache.delegate.flush();
+ $browser.xhr.flush();
expect(log).toEqual('"123";"123";');
- });
+ }));
- it('should clear cache on non GET', function() {
- $browserXhr.expectPOST('abc', {}).respond({});
- cache.data.url = {value:123};
- cache('POST', 'abc', {});
- expect(cache.data.url).toBeUndefined();
- });
+ it('should clear cache on non GET', inject(function($browser, $xhrCache) {
+ $browser.xhr.expectPOST('abc', {}).respond({});
+ $xhrCache.data.url = {value:123};
+ $xhrCache('POST', 'abc', {});
+ expect($xhrCache.data.url).toBeUndefined();
+ }));
- it('should call callback asynchronously for both cache hit and cache miss', function() {
- $browserXhr.expectGET('/url').respond('+');
- cache('GET', '/url', null, callback);
+ it('should call callback asynchronously for both cache hit and cache miss', inject(function($browser, $xhrCache) {
+ $browser.xhr.expectGET('/url').respond('+');
+ $xhrCache('GET', '/url', null, callback);
expect(log).toEqual(''); //callback hasn't executed
- $browserXhr.flush();
+ $browser.xhr.flush();
expect(log).toEqual('"+";'); //callback has executed
- cache('GET', '/url', null, callback);
+ $xhrCache('GET', '/url', null, callback);
expect(log).toEqual('"+";'); //callback hasn't executed
$browser.defer.flush();
expect(log).toEqual('"+";"+";'); //callback has executed
- });
+ }));
- it('should call callback synchronously when sync flag is on', function() {
- $browserXhr.expectGET('/url').respond('+');
- cache('GET', '/url', null, callback, false, true);
+ it('should call callback synchronously when sync flag is on', inject(function($browser, $xhrCache) {
+ $browser.xhr.expectGET('/url').respond('+');
+ $xhrCache('GET', '/url', null, callback, false, true);
expect(log).toEqual(''); //callback hasn't executed
- $browserXhr.flush();
+ $browser.xhr.flush();
expect(log).toEqual('"+";'); //callback has executed
- cache('GET', '/url', null, callback, false, true);
+ $xhrCache('GET', '/url', null, callback, false, true);
expect(log).toEqual('"+";"+";'); //callback has executed
$browser.defer.flush();
expect(log).toEqual('"+";"+";'); //callback was not called again any more
- });
+ }));
- it('should call eval after callbacks for both cache hit and cache miss execute', function() {
- var flushSpy = this.spyOn(scope, '$digest').andCallThrough();
+ it('should call eval after callbacks for both cache hit and cache miss execute',
+ inject(function($browser, $xhrCache, $rootScope) {
+ var flushSpy = this.spyOn($rootScope, '$digest').andCallThrough();
- $browserXhr.expectGET('/url').respond('+');
- cache('GET', '/url', null, callback);
+ $browser.xhr.expectGET('/url').respond('+');
+ $xhrCache('GET', '/url', null, callback);
expect(flushSpy).not.toHaveBeenCalled();
- $browserXhr.flush();
+ $browser.xhr.flush();
expect(flushSpy).toHaveBeenCalled();
flushSpy.reset(); //reset the spy
- cache('GET', '/url', null, callback);
+ $xhrCache('GET', '/url', null, callback);
expect(flushSpy).not.toHaveBeenCalled();
$browser.defer.flush();
expect(flushSpy).toHaveBeenCalled();
- });
+ }));
- it('should call the error callback on error if provided', function() {
+ it('should call the error callback on error if provided', inject(function($browser, $xhrCache) {
var errorSpy = jasmine.createSpy('error'),
successSpy = jasmine.createSpy('success');
- $browserXhr.expectGET('/url').respond(500, 'error');
+ $browser.xhr.expectGET('/url').respond(500, 'error');
- cache('GET', '/url', null, successSpy, errorSpy, false, true);
- $browserXhr.flush();
+ $xhrCache('GET', '/url', null, successSpy, errorSpy, false, true);
+ $browser.xhr.flush();
expect(errorSpy).toHaveBeenCalledWith(500, 'error');
expect(successSpy).not.toHaveBeenCalled();
errorSpy.reset();
- cache('GET', '/url', successSpy, errorSpy, false, true);
- $browserXhr.flush();
+ $xhrCache('GET', '/url', successSpy, errorSpy, false, true);
+ $browser.xhr.flush();
expect(errorSpy).toHaveBeenCalledWith(500, 'error');
expect(successSpy).not.toHaveBeenCalled();
- });
+ }));
- it('should call the $xhr.error on error if error callback not provided', function() {
+ it('should call the $xhr.error on error if error callback not provided',
+ inject(function($browser, $xhrCache, $xhrError) {
var errorSpy = jasmine.createSpy('error'),
successSpy = jasmine.createSpy('success');
- $browserXhr.expectGET('/url').respond(500, 'error');
- cache('GET', '/url', null, successSpy, false, true);
- $browserXhr.flush();
+ $browser.xhr.expectGET('/url').respond(500, 'error');
+ $xhrCache('GET', '/url', null, successSpy, false, true);
+ $browser.xhr.flush();
expect(successSpy).not.toHaveBeenCalled();
- expect($xhrErr).toHaveBeenCalledWith(
+ expect($xhrError).toHaveBeenCalledWith(
{method: 'GET', url: '/url', data: null, success: successSpy},
{status: 500, body: 'error'});
- });
+ }));
});
diff --git a/test/service/xhr.errorSpec.js b/test/service/xhr.errorSpec.js
index 49b63fd0..0ed5ab59 100644
--- a/test/service/xhr.errorSpec.js
+++ b/test/service/xhr.errorSpec.js
@@ -1,22 +1,15 @@
'use strict';
describe('$xhr.error', function() {
- var scope, $browser, $browserXhr, $xhr, $xhrError, log;
+ var log;
- beforeEach(function() {
- scope = angular.scope(angular.service, {
- '$xhr.error': $xhrError = jasmine.createSpy('$xhr.error')
+ beforeEach(inject(function(service) {
+ service('$xhr.error', function(){
+ return jasmine.createSpy('$xhr.error');
});
- $browser = scope.$service('$browser');
- $browserXhr = $browser.xhr;
- $xhr = scope.$service('$xhr');
+ service.alias('$xhr.error', '$xhrError');
log = '';
- });
-
-
- afterEach(function() {
- dealoc(scope);
- });
+ }));
function callback(code, response) {
@@ -25,14 +18,14 @@ describe('$xhr.error', function() {
}
- it('should handle non 200 status codes by forwarding to error handler', function() {
- $browserXhr.expectPOST('/req', 'MyData').respond(500, 'MyError');
+ it('should handle non 200 status codes by forwarding to error handler', inject(function($browser, $xhr, $xhrError) {
+ $browser.xhr.expectPOST('/req', 'MyData').respond(500, 'MyError');
$xhr('POST', '/req', 'MyData', callback);
- $browserXhr.flush();
+ $browser.xhr.flush();
var cb = $xhrError.mostRecentCall.args[0].success;
expect(typeof cb).toEqual('function');
expect($xhrError).toHaveBeenCalledWith(
{url: '/req', method: 'POST', data: 'MyData', success: cb},
{status: 500, body: 'MyError'});
- });
+ }));
});
diff --git a/test/service/xhrSpec.js b/test/service/xhrSpec.js
index 2a552403..997994d7 100644
--- a/test/service/xhrSpec.js
+++ b/test/service/xhrSpec.js
@@ -1,22 +1,16 @@
'use strict';
describe('$xhr', function() {
- var scope, $browser, $browserXhr, $log, $xhr, $xhrErr, log;
-
- beforeEach(function() {
- var scope = angular.scope(angular.service, {
- '$xhr.error': $xhrErr = jasmine.createSpy('xhr.error')});
- $log = scope.$service('$log');
- $browser = scope.$service('$browser');
- $browserXhr = $browser.xhr;
- $xhr = scope.$service('$xhr');
- log = '';
- });
+ var log;
- afterEach(function() {
- dealoc(scope);
- });
+ beforeEach(inject(function(service) {
+ log = '';
+ service('$xhr.error', function(){
+ return jasmine.createSpy('xhr.error');
+ });
+ service.alias('$xhr.error', '$xhrError');
+ }));
function callback(code, response) {
@@ -24,246 +18,246 @@ describe('$xhr', function() {
}
- it('should forward the request to $browser and decode JSON', function() {
- $browserXhr.expectGET('/reqGET').respond('first');
- $browserXhr.expectGET('/reqGETjson').respond('["second"]');
- $browserXhr.expectPOST('/reqPOST', {post:'data'}).respond('third');
+ it('should forward the request to $browser and decode JSON', inject(function($browser, $xhr) {
+ $browser.xhr.expectGET('/reqGET').respond('first');
+ $browser.xhr.expectGET('/reqGETjson').respond('["second"]');
+ $browser.xhr.expectPOST('/reqPOST', {post:'data'}).respond('third');
$xhr('GET', '/reqGET', null, callback);
$xhr('GET', '/reqGETjson', null, callback);
$xhr('POST', '/reqPOST', {post:'data'}, callback);
- $browserXhr.flush();
+ $browser.xhr.flush();
expect(log).toEqual(
'{code=200; response="third"}' +
'{code=200; response=["second"]}' +
'{code=200; response="first"}');
- });
+ }));
- it('should allow all 2xx requests', function() {
- $browserXhr.expectGET('/req1').respond(200, '1');
+ it('should allow all 2xx requests', inject(function($browser, $xhr) {
+ $browser.xhr.expectGET('/req1').respond(200, '1');
$xhr('GET', '/req1', null, callback);
- $browserXhr.flush();
+ $browser.xhr.flush();
- $browserXhr.expectGET('/req2').respond(299, '2');
+ $browser.xhr.expectGET('/req2').respond(299, '2');
$xhr('GET', '/req2', null, callback);
- $browserXhr.flush();
+ $browser.xhr.flush();
expect(log).toEqual(
'{code=200; response="1"}' +
'{code=299; response="2"}');
- });
+ }));
- it('should handle exceptions in callback', function() {
- $browserXhr.expectGET('/reqGET').respond('first');
+ it('should handle exceptions in callback', inject(function($browser, $xhr, $log) {
+ $browser.xhr.expectGET('/reqGET').respond('first');
$xhr('GET', '/reqGET', null, function() { throw "MyException"; });
- $browserXhr.flush();
+ $browser.xhr.flush();
expect($log.error.logs.shift()).toContain('MyException');
- });
+ }));
- it('should automatically deserialize json objects', function() {
+ it('should automatically deserialize json objects', inject(function($browser, $xhr) {
var response;
- $browserXhr.expectGET('/foo').respond('{"foo":"bar","baz":23}');
+ $browser.xhr.expectGET('/foo').respond('{"foo":"bar","baz":23}');
$xhr('GET', '/foo', function(code, resp) {
response = resp;
});
- $browserXhr.flush();
+ $browser.xhr.flush();
expect(response).toEqual({foo:'bar', baz:23});
- });
+ }));
- it('should automatically deserialize json arrays', function() {
+ it('should automatically deserialize json arrays', inject(function($browser, $xhr) {
var response;
- $browserXhr.expectGET('/foo').respond('[1, "abc", {"foo":"bar"}]');
+ $browser.xhr.expectGET('/foo').respond('[1, "abc", {"foo":"bar"}]');
$xhr('GET', '/foo', function(code, resp) {
response = resp;
});
- $browserXhr.flush();
+ $browser.xhr.flush();
expect(response).toEqual([1, 'abc', {foo:'bar'}]);
- });
+ }));
- it('should automatically deserialize json with security prefix', function() {
+ it('should automatically deserialize json with security prefix', inject(function($browser, $xhr) {
var response;
- $browserXhr.expectGET('/foo').respond(')]}\',\n[1, "abc", {"foo":"bar"}]');
+ $browser.xhr.expectGET('/foo').respond(')]}\',\n[1, "abc", {"foo":"bar"}]');
$xhr('GET', '/foo', function(code, resp) {
response = resp;
});
- $browserXhr.flush();
+ $browser.xhr.flush();
expect(response).toEqual([1, 'abc', {foo:'bar'}]);
- });
+ }));
- it('should call $xhr.error on error if no error callback provided', function() {
+ it('should call $xhr.error on error if no error callback provided', inject(function($browser, $xhr, $xhrError) {
var successSpy = jasmine.createSpy('success');
- $browserXhr.expectGET('/url').respond(500, 'error');
+ $browser.xhr.expectGET('/url').respond(500, 'error');
$xhr('GET', '/url', null, successSpy);
- $browserXhr.flush();
+ $browser.xhr.flush();
expect(successSpy).not.toHaveBeenCalled();
- expect($xhrErr).toHaveBeenCalledWith(
+ expect($xhrError).toHaveBeenCalledWith(
{method: 'GET', url: '/url', data: null, success: successSpy},
{status: 500, body: 'error'}
);
- });
+ }));
- it('should call the error callback on error if provided', function() {
+ it('should call the error callback on error if provided', inject(function($browser, $xhr) {
var errorSpy = jasmine.createSpy('error'),
successSpy = jasmine.createSpy('success');
- $browserXhr.expectGET('/url').respond(500, 'error');
+ $browser.xhr.expectGET('/url').respond(500, 'error');
$xhr('GET', '/url', null, successSpy, errorSpy);
- $browserXhr.flush();
+ $browser.xhr.flush();
expect(errorSpy).toHaveBeenCalledWith(500, 'error');
expect(successSpy).not.toHaveBeenCalled();
errorSpy.reset();
$xhr('GET', '/url', successSpy, errorSpy);
- $browserXhr.flush();
+ $browser.xhr.flush();
expect(errorSpy).toHaveBeenCalledWith(500, 'error');
expect(successSpy).not.toHaveBeenCalled();
- });
+ }));
describe('http headers', function() {
describe('default headers', function() {
- it('should set default headers for GET request', function() {
+ it('should set default headers for GET request', inject(function($browser, $xhr) {
var callback = jasmine.createSpy('callback');
- $browserXhr.expectGET('URL', '', {'Accept': 'application/json, text/plain, */*',
+ $browser.xhr.expectGET('URL', '', {'Accept': 'application/json, text/plain, */*',
'X-Requested-With': 'XMLHttpRequest'}).
respond(234, 'OK');
$xhr('GET', 'URL', callback);
- $browserXhr.flush();
+ $browser.xhr.flush();
expect(callback).toHaveBeenCalled();
- });
+ }));
- it('should set default headers for POST request', function() {
+ it('should set default headers for POST request', inject(function($browser, $xhr) {
var callback = jasmine.createSpy('callback');
- $browserXhr.expectPOST('URL', 'xx', {'Accept': 'application/json, text/plain, */*',
+ $browser.xhr.expectPOST('URL', 'xx', {'Accept': 'application/json, text/plain, */*',
'X-Requested-With': 'XMLHttpRequest',
'Content-Type': 'application/x-www-form-urlencoded'}).
respond(200, 'OK');
$xhr('POST', 'URL', 'xx', callback);
- $browserXhr.flush();
+ $browser.xhr.flush();
expect(callback).toHaveBeenCalled();
- });
+ }));
- it('should set default headers for custom HTTP method', function() {
+ it('should set default headers for custom HTTP method', inject(function($browser, $xhr) {
var callback = jasmine.createSpy('callback');
- $browserXhr.expect('FOO', 'URL', '', {'Accept': 'application/json, text/plain, */*',
+ $browser.xhr.expect('FOO', 'URL', '', {'Accept': 'application/json, text/plain, */*',
'X-Requested-With': 'XMLHttpRequest'}).
respond(200, 'OK');
$xhr('FOO', 'URL', callback);
- $browserXhr.flush();
+ $browser.xhr.flush();
expect(callback).toHaveBeenCalled();
- });
+ }));
describe('custom headers', function() {
- it('should allow appending a new header to the common defaults', function() {
+ it('should allow appending a new header to the common defaults', inject(function($browser, $xhr) {
var callback = jasmine.createSpy('callback');
- $browserXhr.expectGET('URL', '', {'Accept': 'application/json, text/plain, */*',
+ $browser.xhr.expectGET('URL', '', {'Accept': 'application/json, text/plain, */*',
'X-Requested-With': 'XMLHttpRequest',
'Custom-Header': 'value'}).
respond(200, 'OK');
$xhr.defaults.headers.common['Custom-Header'] = 'value';
$xhr('GET', 'URL', callback);
- $browserXhr.flush();
+ $browser.xhr.flush();
expect(callback).toHaveBeenCalled();
callback.reset();
- $browserXhr.expectPOST('URL', 'xx', {'Accept': 'application/json, text/plain, */*',
+ $browser.xhr.expectPOST('URL', 'xx', {'Accept': 'application/json, text/plain, */*',
'X-Requested-With': 'XMLHttpRequest',
'Content-Type': 'application/x-www-form-urlencoded',
'Custom-Header': 'value'}).
respond(200, 'OK');
$xhr('POST', 'URL', 'xx', callback);
- $browserXhr.flush();
+ $browser.xhr.flush();
expect(callback).toHaveBeenCalled();
- });
+ }));
- it('should allow appending a new header to a method specific defaults', function() {
+ it('should allow appending a new header to a method specific defaults', inject(function($browser, $xhr) {
var callback = jasmine.createSpy('callback');
- $browserXhr.expectGET('URL', '', {'Accept': 'application/json, text/plain, */*',
+ $browser.xhr.expectGET('URL', '', {'Accept': 'application/json, text/plain, */*',
'X-Requested-With': 'XMLHttpRequest',
'Content-Type': 'application/json'}).
respond(200, 'OK');
$xhr.defaults.headers.get['Content-Type'] = 'application/json';
$xhr('GET', 'URL', callback);
- $browserXhr.flush();
+ $browser.xhr.flush();
expect(callback).toHaveBeenCalled();
callback.reset();
- $browserXhr.expectPOST('URL', 'x', {'Accept': 'application/json, text/plain, */*',
+ $browser.xhr.expectPOST('URL', 'x', {'Accept': 'application/json, text/plain, */*',
'X-Requested-With': 'XMLHttpRequest',
'Content-Type': 'application/x-www-form-urlencoded'}).
respond(200, 'OK');
$xhr('POST', 'URL', 'x', callback);
- $browserXhr.flush();
+ $browser.xhr.flush();
expect(callback).toHaveBeenCalled();
- });
+ }));
- it('should support overwriting and deleting default headers', function() {
+ it('should support overwriting and deleting default headers', inject(function($browser, $xhr) {
var callback = jasmine.createSpy('callback');
- $browserXhr.expectGET('URL', '', {'Accept': 'application/json, text/plain, */*'}).
+ $browser.xhr.expectGET('URL', '', {'Accept': 'application/json, text/plain, */*'}).
respond(200, 'OK');
//delete a default header
delete $xhr.defaults.headers.common['X-Requested-With'];
$xhr('GET', 'URL', callback);
- $browserXhr.flush();
+ $browser.xhr.flush();
expect(callback).toHaveBeenCalled();
callback.reset();
- $browserXhr.expectPOST('URL', 'xx', {'Accept': 'application/json, text/plain, */*',
+ $browser.xhr.expectPOST('URL', 'xx', {'Accept': 'application/json, text/plain, */*',
'Content-Type': 'application/json'}).
respond(200, 'OK');
//overwrite a default header
$xhr.defaults.headers.post['Content-Type'] = 'application/json';
$xhr('POST', 'URL', 'xx', callback);
- $browserXhr.flush();
+ $browser.xhr.flush();
expect(callback).toHaveBeenCalled();
- });
+ }));
});
});
});
describe('xsrf', function() {
- it('should copy the XSRF cookie into a XSRF Header', function() {
+ it('should copy the XSRF cookie into a XSRF Header', inject(function($browser, $xhr) {
var code, response;
- $browserXhr
+ $browser.xhr
.expectPOST('URL', 'DATA', {'X-XSRF-TOKEN': 'secret'})
.respond(234, 'OK');
$browser.cookies('XSRF-TOKEN', 'secret');
@@ -271,9 +265,9 @@ describe('$xhr', function() {
code = c;
response = r;
});
- $browserXhr.flush();
+ $browser.xhr.flush();
expect(code).toEqual(234);
expect(response).toEqual('OK');
- });
+ }));
});
});