var app = angular.module('project', ['restangular', 'ngRoute', 'ngMockE2E']);
app.config(function($routeProvider, RestangularProvider) {
$routeProvider.
when('/', {
controller:ListCtrl,
templateUrl:'list.html'
}).
when('/edit/:projectId', {
controller:EditCtrl,
templateUrl:'detail.html',
resolve: {
project: function(Restangular, $route){
return Restangular.one('projects', $route.current.params.projectId).get();
}
}
}).
when('/new', {controller:CreateCtrl, templateUrl:'detail.html'}).
otherwise({redirectTo:'/'});
RestangularProvider.setBaseUrl('https://api.mongolab.com/api/1/databases/angularjs/collections');
RestangularProvider.setDefaultRequestParams({ apiKey: '4f847ad3e4b08a2eed5f3b54' })
RestangularProvider.setRestangularFields({
id: '_id.$oid'
});
RestangularProvider.setRequestInterceptor(function(elem, operation, what) {
if (operation === 'put') {
elem._id = undefined;
return elem;
}
return elem;
})
});
app.run(function($httpBackend) {
$httpBackend.when(function(method, url, data, headers) {
var data = {method: method, url: url, data: data, headers: headers};
console.log("data", data);
//if(method === "GET") {
return [
{ "_id" : "529f42bce4b0688194263803/529f542ce4b068819426550c" , "name" : "just a test" , "site" : "http://dgfdfg" , "description" : "dgdgx"} ,
{ "_id" : "undefined" , "name" : "test changed" , "description" : "gyfgf" , "site" : "http://www.rawh.bo"} ,
{ "_id" : { "$oid" : "52c6d154e4b0ba6bafa35d4d"} , "name" : "NFL" , "site" : "http://www.nfl.com/" , "description" : "NFL News and Highlights"}
];
//}
});
});
function ListCtrl($scope, Restangular) {
$scope.projects = Restangular.all("projects").getList().$object;
}
function CreateCtrl($scope, $location, Restangular) {
$scope.save = function() {
Restangular.all('projects').post($scope.project).then(function(project) {
$location.path('/list');
});
}
}
function EditCtrl($scope, $location, Restangular, project) {
var original = project;
$scope.project = Restangular.copy(original);
$scope.isClean = function() {
return angular.equals(original, $scope.project);
}
$scope.destroy = function() {
original.remove().then(function() {
$location.path('/list');
});
};
$scope.save = function() {
$scope.project.put().then(function() {
$location.path('/');
});
};
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css" />
<link rel="stylesheet" href="http://getbootstrap.com/2.3.2/assets/css/bootstrap.css">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.4/angular.js"></script>
<script src="http://code.angularjs.org/1.2.4/angular-route.js"></script>
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.4.4/underscore-min.js"></script>
<script type="text/javascript" src="restangular.js"></script>
<script type="text/javascript" src="angular-mocks.js"></script>
<script src="app.js"></script>
</head>
<body>
<div ng-app="project">
<h2><a target="_blank" href="https://github.com/mgonto/restangular">Restangular Example. Click here to check out the library</a></h2>
<h2>JavaScript Projects. <a href="http://angularjs.org/#wire-up-a-backend" target="_blank">Based on AngularJS's sample</a></h2>
<div ng-view></div>
<!-- CACHE FILE: list.html -->
<script type="text/ng-template" id="list.html">
<input type="text" ng-model="search" class="search-query" placeholder="Search">
<table>
<thead>
<tr>
<th>Project</th>
<th>Description</th>
<th><a href="#/new"><i class="icon-plus-sign"></i></a></th>
</tr>
</thead>
<tbody>
<tr ng-repeat="project in projects | filter:search | orderBy:'name'" ng-show="project._id.$oid">
<td><a href="{{project.site}}" target="_blank">{{project.name}}</a></td>
<td>{{project.description}}</td>
<td>
<a href="#/edit/{{project._id.$oid}}"><i class="icon-pencil"></i></a>
</td>
</tr>
</tbody>
</table>
</script>
<!-- CACHE FILE: detail.html -->
<script type="text/ng-template" id="detail.html">
<form name="myForm">
<div class="control-group" ng-class="{error: myForm.name.$invalid}">
<label>Name</label>
<input type="text" name="name" ng-model="project.name" required>
<span ng-show="myForm.name.$error.required" class="help-inline">
Required</span>
</div>
<div class="control-group" ng-class="{error: myForm.site.$invalid}">
<label>Website</label>
<input type="url" name="site" ng-model="project.site" required>
<span ng-show="myForm.site.$error.required" class="help-inline">
Required</span>
<span ng-show="myForm.site.$error.url" class="help-inline">
Not a URL</span>
</div>
<label>Description</label>
<textarea name="description" ng-model="project.description"></textarea>
<br>
<a href="#/" class="btn">Cancel</a>
<button ng-click="save()" ng-disabled="isClean() || myForm.$invalid"
class="btn btn-primary">Save</button>
<button ng-click="destroy()"
ng-show="project._id" class="btn btn-danger">Delete</button>
</form>
</script>
</div>
</body>
</html>
/* Put your css in here */
/**
* Restful Resources service for AngularJS apps
* @version v1.2.0 - 2013-12-09
* @link https://github.com/mgonto/restangular
* @author Martin Gontovnikas <martin@gonto.com.ar>
* @license MIT License, http://www.opensource.org/licenses/MIT
*/
(function() {
var module = angular.module('restangular', []);
module.provider('Restangular', function() {
// Configuration
var Configurer = {};
Configurer.init = function(object, config) {
/**
* Those are HTTP safe methods for which there is no need to pass any data with the request.
*/
object.configuration = config;
var safeMethods= ["get", "head", "options", "trace", "getlist"];
config.isSafe = function(operation) {
return _.contains(safeMethods, operation.toLowerCase());
};
var absolutePattern = /^https?:\/\//i;
config.isAbsoluteUrl = function(string) {
return _.isUndefined(config.absoluteUrl) || _.isNull(config.absoluteUrl) ?
string && absolutePattern.test(string) :
config.absoluteUrl;
}
config.absoluteUrl = _.isUndefined(config.absoluteUrl) ? false : true;
object.setSelfLinkAbsoluteUrl = function(value) {
config.absoluteUrl = value;
}
/**
* This is the BaseURL to be used with Restangular
*/
config.baseUrl = _.isUndefined(config.baseUrl) ? "" : config.baseUrl;
object.setBaseUrl = function(newBaseUrl) {
config.baseUrl = /\/$/.test(newBaseUrl)
? newBaseUrl.substring(0, newBaseUrl.length-1)
: newBaseUrl;
return this;
};
/**
* Sets the extra fields to keep from the parents
*/
config.extraFields = config.extraFields || [];
object.setExtraFields = function(newExtraFields) {
config.extraFields = newExtraFields;
return this;
};
/**
* Some default $http parameter to be used in EVERY call
**/
config.defaultHttpFields = config.defaultHttpFields || {};
object.setDefaultHttpFields = function(values) {
config.defaultHttpFields = values;
return this;
};
config.withHttpValues = function(httpLocalConfig, obj) {
return _.defaults(obj, httpLocalConfig, config.defaultHttpFields);
};
config.encodeIds = _.isUndefined(config.encodeIds) ? true : config.encodeIds;
object.setEncodeIds = function(encode) {
config.encodeIds = encode;
}
config.defaultRequestParams = config.defaultRequestParams || {
get: {},
post: {},
put: {},
remove: {},
common: {}
};
object.setDefaultRequestParams = function(param1, param2) {
var methods = [],
params = param2 || param1;
if (!_.isUndefined(param2)) {
if (_.isArray(param1)) {
methods = param1;
} else {
methods.push(param1);
}
} else {
methods.push('common');
}
_.each(methods, function (method) {
config.defaultRequestParams[method] = params;
});
return this;
}
object.requestParams = config.defaultRequestParams;
config.defaultHeaders = config.defaultHeaders || {};
object.setDefaultHeaders = function(headers) {
config.defaultHeaders = headers;
object.defaultHeaders = config.defaultHeaders;
return this;
};
object.defaultHeaders = config.defaultHeaders;
/**
* Method overriders will set which methods are sent via POST with an X-HTTP-Method-Override
**/
config.methodOverriders = config.methodOverriders || [];
object.setMethodOverriders = function(values) {
var overriders = _.extend([], values);
if (config.isOverridenMethod('delete', overriders)) {
overriders.push("remove");
}
config.methodOverriders = overriders;
return this;
};
config.isOverridenMethod = function(method, values) {
var search = values || config.methodOverriders;
return !_.isUndefined(_.find(search, function(one) {
return one.toLowerCase() === method.toLowerCase();
}));
};
/**
* Sets the URL creator type. For now, only Path is created. In the future we'll have queryParams
**/
config.urlCreator = config.urlCreator || "path";
object.setUrlCreator = function(name) {
if (!_.has(config.urlCreatorFactory, name)) {
throw new Error("URL Path selected isn't valid");
}
config.urlCreator = name;
return this;
};
/**
* You can set the restangular fields here. The 3 required fields for Restangular are:
*
* id: Id of the element
* route: name of the route of this element
* parentResource: the reference to the parent resource
*
* All of this fields except for id, are handled (and created) by Restangular. By default,
* the field values will be id, route and parentResource respectively
*/
config.restangularFields = config.restangularFields || {
id: "id",
route: "route",
parentResource: "parentResource",
restangularCollection: "restangularCollection",
cannonicalId: "__cannonicalId",
etag: "restangularEtag",
selfLink: "href",
get: "get",
getList: "getList",
put: "put",
post: "post",
remove: "remove",
head: "head",
trace: "trace",
options: "options",
patch: "patch",
getRestangularUrl: "getRestangularUrl",
getRequestedUrl: "getRequestedUrl",
putElement: "putElement",
addRestangularMethod: "addRestangularMethod",
getParentList: "getParentList",
clone: "clone",
ids: "ids",
httpConfig: '_$httpConfig',
reqParams: 'reqParams',
one: 'one',
all: 'all',
several: 'several',
oneUrl: 'oneUrl',
allUrl: 'allUrl',
customPUT: 'customPUT',
customPOST: 'customPOST',
customDELETE: 'customDELETE',
customGET: 'customGET',
doPUT: 'doPUT',
doPOST: 'doPOST',
doDELETE: 'doDELETE',
doGET: 'doGET'
};
object.setRestangularFields = function(resFields) {
config.restangularFields =
_.extend(config.restangularFields, resFields);
return this;
};
config.isRestangularized = function(obj) {
return !!obj[config.restangularFields.one] || !!obj[config.restangularFields.all];
}
config.setFieldToElem = function(field, elem, value) {
var properties = field.split('.');
var idValue = elem;
_.each(_.initial(properties), function(prop) {
idValue[prop] = {};
idValue = idValue[prop];
});
idValue[_.last(properties)] = value;
return this;
};
config.getFieldFromElem = function(field, elem) {
var properties = field.split('.');
var idValue = angular.copy(elem);
_.each(properties, function(prop) {
if (idValue) {
idValue = idValue[prop];
}
});
return idValue;
};
config.setIdToElem = function(elem, id) {
config.setFieldToElem(config.restangularFields.id, elem, id);
return this;
};
config.getIdFromElem = function(elem) {
return config.getFieldFromElem(config.restangularFields.id, elem);
};
config.isValidId = function(elemId) {
return "" !== elemId && !_.isUndefined(elemId) && !_.isNull(elemId)
}
config.setUrlToElem = function(elem, url) {
config.setFieldToElem(config.restangularFields.selfLink, elem, url);
return this;
}
config.getUrlFromElem = function(elem) {
return config.getFieldFromElem(config.restangularFields.selfLink, elem);
}
config.useCannonicalId = _.isUndefined(config.useCannonicalId) ? false : config.useCannonicalId;
object.setUseCannonicalId = function(value) {
config.useCannonicalId = value;
return this;
}
config.getCannonicalIdFromElem = function(elem) {
var cannonicalId = elem[config.restangularFields.cannonicalId];
var actualId = config.isValidId(cannonicalId) ?
cannonicalId : config.getIdFromElem(elem);
return actualId;
};
/**
* Sets the Response parser. This is used in case your response isn't directly the data.
* For example if you have a response like {meta: {'meta'}, data: {name: 'Gonto'}}
* you can extract this data which is the one that needs wrapping
*
* The ResponseExtractor is a function that receives the response and the method executed.
*/
config.responseExtractor = config.responseExtractor || function(data, operation,
what, url, response, deferred) {
return data;
};
object.setResponseExtractor = function(extractor) {
config.responseExtractor = extractor;
return this;
};
object.setResponseInterceptor = object.setResponseExtractor;
/**
* Response interceptor is called just before resolving promises.
*/
/**
* Request interceptor is called before sending an object to the server.
*/
config.fullRequestInterceptor = config.fullRequestInterceptor || function(element, operation,
path, url, headers, params, httpConfig) {
return {
element: element,
headers: headers,
params: params,
httpConfig: httpConfig
};
};
object.setRequestInterceptor = function(interceptor) {
config.fullRequestInterceptor = function(elem, operation, path, url, headers, params, httpConfig) {
return {
headers: headers,
params: params,
element: interceptor(elem, operation, path, url),
httpConfig: httpConfig
}
};
return this;
};
object.setFullRequestInterceptor = function(interceptor) {
config.fullRequestInterceptor = interceptor;
return this;
};
config.errorInterceptor = config.errorInterceptor || function() {};
object.setErrorInterceptor = function(interceptor) {
config.errorInterceptor = interceptor;
return this;
};
config.onBeforeElemRestangularized = config.onBeforeElemRestangularized || function(elem) {
return elem;
}
object.setOnBeforeElemRestangularized = function(post) {
config.onBeforeElemRestangularized = post;
return this;
};
/**
* This method is called after an element has been "Restangularized".
*
* It receives the element, a boolean indicating if it's an element or a collection
* and the name of the model
*
*/
config.onElemRestangularized = config.onElemRestangularized || function(elem) {
return elem;
};
object.setOnElemRestangularized = function(post) {
config.onElemRestangularized = post;
return this;
};
/**
* Depracated. Don't use this!!
*/
object.setListTypeIsArray = function(val) {
};
config.shouldSaveParent = config.shouldSaveParent || function() {
return true;
};
object.setParentless = function(values) {
if (_.isArray(values)) {
config.shouldSaveParent = function(route) {
return !_.contains(values, route);
}
} else if (_.isBoolean(values)) {
config.shouldSaveParent = function() {
return !values;
}
}
return this;
};
/**
* This lets you set a suffix to every request.
*
* For example, if your api requires that for JSon requests you do /users/123.json, you can set that
* in here.
*
*
* By default, the suffix is null
*/
config.suffix = _.isUndefined(config.suffix) ? null : config.suffix;
object.setRequestSuffix = function(newSuffix) {
config.suffix = newSuffix;
return this;
};
/**
* Add element transformers for certain routes.
*/
config.transformers = config.transformers || {};
object.addElementTransformer = function(type, secondArg, thirdArg) {
var isCollection = null;
var transformer = null;
if (arguments.length === 2) {
transformer = secondArg;
} else {
transformer = thirdArg;
isCollection = secondArg;
}
var typeTransformers = config.transformers[type];
if (!typeTransformers) {
typeTransformers = config.transformers[type] = [];
}
typeTransformers.push(function(coll, elem) {
if (_.isNull(isCollection) || (coll == isCollection)) {
return transformer(elem);
}
return elem;
});
};
object.extendCollection = function(route, fn) {
return object.addElementTransformer(route, true, fn);
};
object.extendModel = function(route, fn) {
return object.addElementTransformer(route, false, fn);
};
config.transformElem = function(elem, isCollection, route, Restangular) {
var typeTransformers = config.transformers[route];
var changedElem = elem;
if (typeTransformers) {
_.each(typeTransformers, function(transformer) {
changedElem = transformer(isCollection, changedElem);
});
}
return config.onElemRestangularized(changedElem,
isCollection, route, Restangular);
};
config.fullResponse = _.isUndefined(config.fullResponse) ? false : config.fullResponse;
object.setFullResponse = function(full) {
config.fullResponse = full;
return this;
};
//Internal values and functions
config.urlCreatorFactory = {};
/**
* Base URL Creator. Base prototype for everything related to it
**/
var BaseCreator = function() {
};
BaseCreator.prototype.setConfig = function(config) {
this.config = config;
return this;
};
BaseCreator.prototype.parentsArray = function(current) {
var parents = [];
while(current) {
parents.push(current);
current = current[this.config.restangularFields.parentResource];
}
return parents.reverse();
};
function RestangularResource(config, $http, url, configurer) {
var resource = {};
_.each(_.keys(configurer), function(key) {
var value = configurer[key];
// Add default parameters
value.params = _.extend({}, value.params,
config.defaultRequestParams[value.method.toLowerCase()]);
// We don't want the ? if no params are there
if (_.isEmpty(value.params)) {
delete value.params;
}
if (config.isSafe(value.method)) {
resource[key] = function() {
return $http(_.extend(value, {
url: url
}));
}
} else {
resource[key] = function(data) {
return $http(_.extend(value, {
url: url,
data: data
}));
}
}
});
return resource;
}
BaseCreator.prototype.resource = function(current, $http, localHttpConfig, callHeaders, callParams, what, etag, operation) {
var params = _.defaults(callParams || {}, this.config.defaultRequestParams.common);
var headers = _.defaults(callHeaders || {}, this.config.defaultHeaders);
if (etag) {
if (!config.isSafe(operation)) {
headers['If-Match'] = etag;
} else {
headers['If-None-Match'] = etag;
}
}
var url = this.base(current);
if (what) {
var add = '';
if (!/\/$/.test(url)) {
add += '/';
}
add += what;
url += add;
}
if (this.config.suffix
&& url.indexOf(this.config.suffix, url.length - this.config.suffix.length) === -1
&& !this.config.getUrlFromElem(current)) {
url += this.config.suffix;
}
current[this.config.restangularFields.httpConfig] = undefined;
return RestangularResource(this.config, $http, url, {
getList: this.config.withHttpValues(localHttpConfig,
{method: 'GET',
params: params,
headers: headers}),
get: this.config.withHttpValues(localHttpConfig,
{method: 'GET',
params: params,
headers: headers}),
put: this.config.withHttpValues(localHttpConfig,
{method: 'PUT',
params: params,
headers: headers}),
post: this.config.withHttpValues(localHttpConfig,
{method: 'POST',
params: params,
headers: headers}),
remove: this.config.withHttpValues(localHttpConfig,
{method: 'DELETE',
params: params,
headers: headers}),
head: this.config.withHttpValues(localHttpConfig,
{method: 'HEAD',
params: params,
headers: headers}),
trace: this.config.withHttpValues(localHttpConfig,
{method: 'TRACE',
params: params,
headers: headers}),
options: this.config.withHttpValues(localHttpConfig,
{method: 'OPTIONS',
params: params,
headers: headers}),
patch: this.config.withHttpValues(localHttpConfig,
{method: 'PATCH',
params: params,
headers: headers})
});
};
/**
* This is the Path URL creator. It uses Path to show Hierarchy in the Rest API.
* This means that if you have an Account that then has a set of Buildings, a URL to a building
* would be /accounts/123/buildings/456
**/
var Path = function() {
};
Path.prototype = new BaseCreator();
Path.prototype.base = function(current) {
var __this = this;
return _.reduce(this.parentsArray(current), function(acum, elem) {
var elemUrl;
var elemSelfLink = __this.config.getUrlFromElem(elem);
if (elemSelfLink) {
if (__this.config.isAbsoluteUrl(elemSelfLink)) {
return elemSelfLink;
} else {
elemUrl = elemSelfLink;
}
} else {
elemUrl = elem[__this.config.restangularFields.route];
if (elem[__this.config.restangularFields.restangularCollection]) {
var ids = elem[__this.config.restangularFields.ids];
if (ids) {
elemUrl += "/" + ids.join(",");
}
} else {
var elemId;
if (__this.config.useCannonicalId) {
elemId = __this.config.getCannonicalIdFromElem(elem);
} else {
elemId = __this.config.getIdFromElem(elem);
}
if (config.isValidId(elemId)) {
elemUrl += "/" + (__this.config.encodeIds ? encodeURIComponent(elemId) : elemId);
}
}
}
return acum + "/" + elemUrl;
}, this.config.baseUrl);
};
Path.prototype.fetchUrl = function(current, what) {
var baseUrl = this.base(current);
if (what) {
baseUrl += "/" + what;
}
return baseUrl;
};
Path.prototype.fetchRequestedUrl = function(current, what) {
var url = this.fetchUrl(current, what);
var params = current[config.restangularFields.reqParams];
// From here on and until the end of fetchRequestedUrl,
// the code has been kindly borrowed from angular.js
// The reason for such code bloating is coherence:
// If the user were to use this for cache management, the
// serialization of parameters would need to be identical
// to the one done by angular for cache keys to match.
function sortedKeys(obj) {
var keys = [];
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
keys.push(key);
}
}
return keys.sort();
}
function forEachSorted(obj, iterator, context) {
var keys = sortedKeys(obj);
for ( var i = 0; i < keys.length; i++) {
iterator.call(context, obj[keys[i]], keys[i]);
}
return keys;
}
function encodeUriQuery(val, pctEncodeSpaces) {
return encodeURIComponent(val).
replace(/%40/gi, '@').
replace(/%3A/gi, ':').
replace(/%24/g, '$').
replace(/%2C/gi, ',').
replace(/%20/g, (pctEncodeSpaces ? '%20' : '+'));
}
if (!params) return url;
var parts = [];
forEachSorted(params, function(value, key) {
if (value == null || value == undefined) return;
if (!angular.isArray(value)) value = [value];
angular.forEach(value, function(v) {
if (angular.isObject(v)) {
v = angular.toJson(v);
}
parts.push(encodeUriQuery(key) + '=' +
encodeUriQuery(v));
});
});
return url + ((url.indexOf('?') === -1) ? '?' : '&') + parts.join('&');
};
config.urlCreatorFactory.path = Path;
}
var globalConfiguration = {};
Configurer.init(this, globalConfiguration);
this.$get = ['$http', '$q', function($http, $q) {
function createServiceForConfiguration(config) {
var service = {};
var urlHandler = new config.urlCreatorFactory[config.urlCreator]();
urlHandler.setConfig(config);
function restangularizeBase(parent, elem, route, reqParams) {
elem[config.restangularFields.route] = route;
elem[config.restangularFields.getRestangularUrl] = _.bind(urlHandler.fetchUrl, urlHandler, elem);
elem[config.restangularFields.getRequestedUrl] = _.bind(urlHandler.fetchRequestedUrl, urlHandler, elem);
elem[config.restangularFields.addRestangularMethod] = _.bind(addRestangularMethodFunction, elem);
elem[config.restangularFields.clone] = _.bind(copyRestangularizedElement, elem, elem);
elem[config.restangularFields.reqParams] = _.isEmpty(reqParams) ? null : reqParams;
elem.withHttpConfig = _.bind(withHttpConfig, elem);
// RequestLess connection
elem[config.restangularFields.one] = _.bind(one, elem, elem);
elem[config.restangularFields.all] = _.bind(all, elem, elem);
elem[config.restangularFields.several] = _.bind(several, elem, elem);
elem[config.restangularFields.oneUrl] = _.bind(oneUrl, elem, elem);
elem[config.restangularFields.allUrl] = _.bind(allUrl, elem, elem);
if (parent && config.shouldSaveParent(route)) {
var parentId = config.getIdFromElem(parent);
var parentUrl = config.getUrlFromElem(parent);
var restangularFieldsForParent = _.union(
_.values( _.pick(config.restangularFields, ['route', 'parentResource']) ),
config.extraFields
);
var parentResource = _.pick(parent, restangularFieldsForParent);
if (config.isValidId(parentId)) {
config.setIdToElem(parentResource, parentId);
}
if (config.isValidId(parentUrl)) {
config.setUrlToElem(parentResource, parentUrl);
}
elem[config.restangularFields.parentResource] = parentResource;
} else {
elem[config.restangularFields.parentResource] = null;
}
return elem;
}
function one(parent, route, id) {
var elem = {};
config.setIdToElem(elem, id);
return restangularizeElem(parent, elem , route);
}
function all(parent, route) {
return restangularizeCollection(parent, [] , route, true);
}
function several(parent, route, ids) {
var collection = [];
collection[config.restangularFields.ids] =
Array.prototype.splice.call(arguments, 2);
return restangularizeCollection(parent, collection , route, true);
}
function oneUrl(parent, route, url) {
var elem = {};
config.setUrlToElem(elem, url);
return restangularizeElem(parent, elem , route);
}
function allUrl(parent, route, url) {
var elem = {};
config.setUrlToElem(elem, url);
return restangularizeCollection(parent, elem , route, true);
}
// Promises
function restangularizePromise(promise, isCollection, valueToFill) {
promise.call = _.bind(promiseCall, promise);
promise.get = _.bind(promiseGet, promise);
promise[config.restangularFields.restangularCollection] = isCollection;
if (isCollection) {
promise.push = _.bind(promiseCall, promise, "push");
}
promise.$object = valueToFill;
return promise;
}
function promiseCall(method) {
var deferred = $q.defer();
var callArgs = arguments;
var filledValue = {};
this.then(function(val) {
var params = Array.prototype.slice.call(callArgs, 1);
var func = val[method];
func.apply(val, params);
filledValue = val;
deferred.resolve(val);
});
return restangularizePromise(deferred.promise, this[config.restangularFields.restangularCollection], filledValue);
}
function promiseGet(what) {
var deferred = $q.defer();
var filledValue = {};
this.then(function(val) {
filledValue = val[what];
deferred.resolve(filledValue);
});
return restangularizePromise(deferred.promise, this[config.restangularFields.restangularCollection], filledValue);
}
function resolvePromise(deferred, response, data, filledValue) {
_.extend(filledValue, data);
// Trigger the full response interceptor.
if (config.fullResponse) {
return deferred.resolve(_.extend(response, {
data: data
}));
} else {
deferred.resolve(data);
}
}
// Elements
function stripRestangular(elem) {
if (_.isArray(elem)) {
var array = [];
_.each(elem, function(value) {
array.push(stripRestangular(value));
});
return array;
} else {
return _.omit(elem, _.values(_.omit(config.restangularFields, 'id')));
}
}
function addCustomOperation(elem) {
elem.customOperation = _.bind(customFunction, elem);
_.each(["put", "post", "get", "delete"], function(oper) {
_.each(["do", "custom"], function(alias) {
var callOperation = oper === 'delete' ? 'remove' : oper;
var name = alias + oper.toUpperCase();
var callFunction;
if (callOperation !== 'put' && callOperation !== 'post') {
callFunction = customFunction;
} else {
callFunction = function(operation, elem, path, params, headers) {
return _.bind(customFunction, this)(operation, path, params, headers, elem);
}
}
elem[name] = _.bind(callFunction, elem, callOperation);
});
});
elem.customGETLIST = _.bind(fetchFunction, elem);
elem.doGETLIST = elem.customGETLIST;
}
function copyRestangularizedElement(fromElement) {
var copiedElement = angular.copy(fromElement);
return restangularizeElem(copiedElement[config.restangularFields.parentResource],
copiedElement, copiedElement[config.restangularFields.route]);
}
function restangularizeElem(parent, element, route, collection, reqParams) {
var elem = config.onBeforeElemRestangularized(element, false, route);
var localElem = restangularizeBase(parent, elem, route, reqParams);
if (config.useCannonicalId) {
localElem[config.restangularFields.cannonicalId] = config.getIdFromElem(localElem)
}
if (collection) {
localElem[config.restangularFields.getParentList] = function() {
return collection;
}
}
localElem[config.restangularFields.restangularCollection] = false;
localElem[config.restangularFields.get] = _.bind(getFunction, localElem);
localElem[config.restangularFields.getList] = _.bind(fetchFunction, localElem);
localElem[config.restangularFields.put] = _.bind(putFunction, localElem);
localElem[config.restangularFields.post] = _.bind(postFunction, localElem);
localElem[config.restangularFields.remove] = _.bind(deleteFunction, localElem);
localElem[config.restangularFields.head] = _.bind(headFunction, localElem);
localElem[config.restangularFields.trace] = _.bind(traceFunction, localElem);
localElem[config.restangularFields.options] = _.bind(optionsFunction, localElem);
localElem[config.restangularFields.patch] = _.bind(patchFunction, localElem);
addCustomOperation(localElem);
return config.transformElem(localElem, false, route, service);
}
function restangularizeCollection(parent, element, route, reqParams) {
var elem = config.onBeforeElemRestangularized(element, true, route);
var localElem = restangularizeBase(parent, elem, route, reqParams);
localElem[config.restangularFields.restangularCollection] = true;
localElem[config.restangularFields.post] = _.bind(postFunction, localElem, null);
localElem[config.restangularFields.remove] = _.bind(deleteFunction, localElem);
localElem[config.restangularFields.head] = _.bind(headFunction, localElem);
localElem[config.restangularFields.trace] = _.bind(traceFunction, localElem);
localElem[config.restangularFields.putElement] = _.bind(putElementFunction, localElem);
localElem[config.restangularFields.options] = _.bind(optionsFunction, localElem);
localElem[config.restangularFields.patch] = _.bind(patchFunction, localElem);
localElem[config.restangularFields.get] = _.bind(getById, localElem);
localElem[config.restangularFields.getList] = _.bind(fetchFunction, localElem, null);
addCustomOperation(localElem);
return config.transformElem(localElem, true, route, service);
}
function getById(id, reqParams, headers){
return this.customGET(id.toString(), reqParams, headers);
}
function putElementFunction(idx, params, headers) {
var __this = this;
var elemToPut = this[idx];
var deferred = $q.defer();
var filledArray = [];
elemToPut.put(params, headers).then(function(serverElem) {
var newArray = copyRestangularizedElement(__this);
newArray[idx] = serverElem;
filledArray = newArray;
deferred.resolve(newArray);
}, function(response) {
deferred.reject(response);
});
return restangularizePromise(deferred.promise, true, filledArray);
}
function parseResponse(resData, operation, route, fetchUrl, response, deferred) {
var data = config.responseExtractor(resData, operation, route, fetchUrl, response, deferred);
var etag = response.headers("ETag");
if (data && etag) {
data[config.restangularFields.etag] = etag;
}
return data;
}
function fetchFunction(what, reqParams, headers) {
var __this = this;
var deferred = $q.defer();
var operation = 'getList';
var url = urlHandler.fetchUrl(this, what);
var whatFetched = what || __this[config.restangularFields.route];
var request = config.fullRequestInterceptor(null, operation,
whatFetched, url, headers || {}, reqParams || {}, this[config.restangularFields.httpConfig] || {});
var filledArray = [];
urlHandler.resource(this, $http, request.httpConfig, request.headers, request.params, what,
this[config.restangularFields.etag], operation).getList().then(function(response) {
var resData = response.data;
var fullParams = response.config.params;
var data = parseResponse(resData, operation, whatFetched, url, response, deferred);
var processedData = _.map(data, function(elem) {
if (!__this[config.restangularFields.restangularCollection]) {
return restangularizeElem(__this, elem, what, data);
} else {
return restangularizeElem(__this[config.restangularFields.parentResource],
elem, __this[config.restangularFields.route], data);
}
});
processedData = _.extend(data, processedData);
if (!__this[config.restangularFields.restangularCollection]) {
resolvePromise(deferred, response, restangularizeCollection(__this, processedData, what, fullParams), filledArray);
} else {
resolvePromise(deferred, response, restangularizeCollection(__this[config.restangularFields.parentResource], processedData, __this[config.restangularFields.route], fullParams), filledArray);
}
}, function error(response) {
if ( config.errorInterceptor(response) !== false ) {
deferred.reject(response);
}
});
return restangularizePromise(deferred.promise, true, filledArray);
}
function withHttpConfig(httpConfig) {
this[config.restangularFields.httpConfig] = httpConfig;
return this;
}
function elemFunction(operation, what, params, obj, headers) {
var __this = this;
var deferred = $q.defer();
var resParams = params || {};
var route = what || this[config.restangularFields.route];
var fetchUrl = urlHandler.fetchUrl(this, what);
var callObj = obj || this;
var etag = callObj[config.restangularFields.etag];
if (_.isObject(callObj) && config.isRestangularized(callObj)) {
callObj = stripRestangular(callObj);
}
var request = config.fullRequestInterceptor(callObj, operation, route, fetchUrl,
headers || {}, resParams || {}, this[config.restangularFields.httpConfig] || {});
var filledObject = {};
var okCallback = function(response) {
var resData = response.data;
var fullParams = response.config.params;
var elem = parseResponse(resData, operation, route, fetchUrl, response, deferred);
if (elem) {
if (operation === "post" && !__this[config.restangularFields.restangularCollection]) {
resolvePromise(deferred, response, restangularizeElem(__this, elem, what, fullParams), filledObject);
} else {
resolvePromise(deferred, response, restangularizeElem(__this[config.restangularFields.parentResource], elem, __this[config.restangularFields.route], fullParams), filledObject);
}
} else {
resolvePromise(deferred, response, undefined, filledObject);
}
};
var errorCallback = function(response) {
if ( config.errorInterceptor(response) !== false ) {
deferred.reject(response);
}
};
// Overring HTTP Method
var callOperation = operation;
var callHeaders = _.extend({}, request.headers);
var isOverrideOperation = config.isOverridenMethod(operation);
if (isOverrideOperation) {
callOperation = 'post';
callHeaders = _.extend(callHeaders, {'X-HTTP-Method-Override': operation === 'remove' ? 'DELETE' : operation});
}
if (config.isSafe(operation)) {
if (isOverrideOperation) {
urlHandler.resource(this, $http, request.httpConfig, callHeaders, request.params,
what, etag, callOperation)[callOperation]({}).then(okCallback, errorCallback);
} else {
urlHandler.resource(this, $http, request.httpConfig, callHeaders, request.params,
what, etag, callOperation)[callOperation]().then(okCallback, errorCallback);
}
} else {
urlHandler.resource(this, $http, request.httpConfig, callHeaders, request.params,
what, etag, callOperation)[callOperation](request.element).then(okCallback, errorCallback);
}
return restangularizePromise(deferred.promise, false, filledObject);
}
function getFunction(params, headers) {
return _.bind(elemFunction, this)("get", undefined, params, undefined, headers);
}
function deleteFunction(params, headers) {
return _.bind(elemFunction, this)("remove", undefined, params, undefined, headers);
}
function putFunction(params, headers) {
return _.bind(elemFunction, this)("put", undefined, params, undefined, headers);
}
function postFunction(what, elem, params, headers) {
return _.bind(elemFunction, this)("post", what, params, elem, headers);
}
function headFunction(params, headers) {
return _.bind(elemFunction, this)("head", undefined, params, undefined, headers);
}
function traceFunction(params, headers) {
return _.bind(elemFunction, this)("trace", undefined, params, undefined, headers);
}
function optionsFunction(params, headers) {
return _.bind(elemFunction, this)("options", undefined, params, undefined, headers);
}
function patchFunction(elem, params, headers) {
return _.bind(elemFunction, this)("patch", undefined, params, elem, headers);
}
function customFunction(operation, path, params, headers, elem) {
return _.bind(elemFunction, this)(operation, path, params, elem, headers);
}
function addRestangularMethodFunction(name, operation, path, defaultParams, defaultHeaders, defaultElem) {
var bindedFunction;
if (operation === 'getList') {
bindedFunction = _.bind(fetchFunction, this, path);
} else {
bindedFunction = _.bind(customFunction, this, operation, path);
}
var createdFunction = function(params, headers, elem) {
var callParams = _.defaults({
params: params,
headers: headers,
elem: elem
}, {
params: defaultParams,
headers: defaultHeaders,
elem: defaultElem
});
return bindedFunction(callParams.params, callParams.headers, callParams.elem);
};
if (config.isSafe(operation)) {
this[name] = createdFunction;
} else {
this[name] = function(elem, params, headers) {
return createdFunction(params, headers, elem);
}
}
}
function withConfigurationFunction(configurer) {
var newConfig = angular.copy(config);
Configurer.init(newConfig, newConfig);
configurer(newConfig);
return createServiceForConfiguration(newConfig);
}
Configurer.init(service, config);
service.copy = _.bind(copyRestangularizedElement, service);
service.withConfig = _.bind(withConfigurationFunction, service);
service.one = _.bind(one, service, null);
service.all = _.bind(all, service, null);
service.several = _.bind(several, service, null);
service.oneUrl = _.bind(oneUrl, service, null);
service.allUrl = _.bind(allUrl, service, null);
service.stripRestangular = _.bind(stripRestangular, service);
service.restangularizeElement = _.bind(restangularizeElem, service);
service.restangularizeCollection = _.bind(restangularizeCollection, service);
return service;
}
return createServiceForConfiguration(globalConfiguration);
}];
}
);
})();
/**
* @license AngularJS v1.1.1
* (c) 2010-2012 Google, Inc. http://angularjs.org
* License: MIT
*
* TODO(vojta): wrap whole file into closure during build
*/
/**
* @ngdoc overview
* @name angular.mock
* @description
*
* Namespace from 'angular-mocks.js' which contains testing related code.
*/
angular.mock = {};
/**
* ! This is a private undocumented service !
*
* @name ngMock.$browser
*
* @description
* This service is a mock implementation of {@link ng.$browser}. It provides fake
* implementation for commonly used browser apis that are hard to test, e.g. setTimeout, xhr,
* cookies, etc...
*
* The api of this service is the same as that of the real {@link ng.$browser $browser}, except
* that there are several helper methods available which can be used in tests.
*/
angular.mock.$BrowserProvider = function() {
this.$get = function(){
return new angular.mock.$Browser();
};
};
angular.mock.$Browser = function() {
var self = this;
this.isMock = true;
self.$$url = "http://server/";
self.$$lastUrl = self.$$url; // used by url polling fn
self.pollFns = [];
// TODO(vojta): remove this temporary api
self.$$completeOutstandingRequest = angular.noop;
self.$$incOutstandingRequestCount = angular.noop;
// register url polling fn
self.onUrlChange = function(listener) {
self.pollFns.push(
function() {
if (self.$$lastUrl != self.$$url) {
self.$$lastUrl = self.$$url;
listener(self.$$url);
}
}
);
return listener;
};
self.cookieHash = {};
self.lastCookieHash = {};
self.deferredFns = [];
self.deferredNextId = 0;
self.defer = function(fn, delay) {
delay = delay || 0;
self.deferredFns.push({time:(self.defer.now + delay), fn:fn, id: self.deferredNextId});
self.deferredFns.sort(function(a,b){ return a.time - b.time;});
return self.deferredNextId++;
};
self.defer.now = 0;
self.defer.cancel = function(deferId) {
var fnIndex;
angular.forEach(self.deferredFns, function(fn, index) {
if (fn.id === deferId) fnIndex = index;
});
if (fnIndex !== undefined) {
self.deferredFns.splice(fnIndex, 1);
return true;
}
return false;
};
/**
* @name ngMock.$browser#defer.flush
* @methodOf ngMock.$browser
*
* @description
* Flushes all pending requests and executes the defer callbacks.
*
* @param {number=} number of milliseconds to flush. See {@link #defer.now}
*/
self.defer.flush = function(delay) {
if (angular.isDefined(delay)) {
self.defer.now += delay;
} else {
if (self.deferredFns.length) {
self.defer.now = self.deferredFns[self.deferredFns.length-1].time;
} else {
throw Error('No deferred tasks to be flushed');
}
}
while (self.deferredFns.length && self.deferredFns[0].time <= self.defer.now) {
self.deferredFns.shift().fn();
}
};
/**
* @name ngMock.$browser#defer.now
* @propertyOf ngMock.$browser
*
* @description
* Current milliseconds mock time.
*/
self.$$baseHref = '';
self.baseHref = function() {
return this.$$baseHref;
};
};
angular.mock.$Browser.prototype = {
/**
* @name ngMock.$browser#poll
* @methodOf ngMock.$browser
*
* @description
* run all fns in pollFns
*/
poll: function poll() {
angular.forEach(this.pollFns, function(pollFn){
pollFn();
});
},
addPollFn: function(pollFn) {
this.pollFns.push(pollFn);
return pollFn;
},
url: function(url, replace) {
if (url) {
this.$$url = url;
return this;
}
return this.$$url;
},
cookies: function(name, value) {
if (name) {
if (value == undefined) {
delete this.cookieHash[name];
} else {
if (angular.isString(value) && //strings only
value.length <= 4096) { //strict cookie storage limits
this.cookieHash[name] = value;
}
}
} else {
if (!angular.equals(this.cookieHash, this.lastCookieHash)) {
this.lastCookieHash = angular.copy(this.cookieHash);
this.cookieHash = angular.copy(this.cookieHash);
}
return this.cookieHash;
}
},
notifyWhenNoOutstandingRequests: function(fn) {
fn();
}
};
/**
* @ngdoc object
* @name ngMock.$exceptionHandlerProvider
*
* @description
* Configures the mock implementation of {@link ng.$exceptionHandler} to rethrow or to log errors passed
* into the `$exceptionHandler`.
*/
/**
* @ngdoc object
* @name ngMock.$exceptionHandler
*
* @description
* Mock implementation of {@link ng.$exceptionHandler} that rethrows or logs errors passed
* into it. See {@link ngMock.$exceptionHandlerProvider $exceptionHandlerProvider} for configuration
* information.
*/
angular.mock.$ExceptionHandlerProvider = function() {
var handler;
/**
* @ngdoc method
* @name ngMock.$exceptionHandlerProvider#mode
* @methodOf ngMock.$exceptionHandlerProvider
*
* @description
* Sets the logging mode.
*
* @param {string} mode Mode of operation, defaults to `rethrow`.
*
* - `rethrow`: If any errors are are passed into the handler in tests, it typically
* means that there is a bug in the application or test, so this mock will
* make these tests fail.
* - `log`: Sometimes it is desirable to test that an error is throw, for this case the `log` mode stores the
* error and allows later assertion of it.
* See {@link ngMock.$log#assertEmpty assertEmpty()} and
* {@link ngMock.$log#reset reset()}
*/
this.mode = function(mode) {
switch(mode) {
case 'rethrow':
handler = function(e) {
throw e;
};
break;
case 'log':
var errors = [];
handler = function(e) {
if (arguments.length == 1) {
errors.push(e);
} else {
errors.push([].slice.call(arguments, 0));
}
};
handler.errors = errors;
break;
default:
throw Error("Unknown mode '" + mode + "', only 'log'/'rethrow' modes are allowed!");
}
};
this.$get = function() {
return handler;
};
this.mode('rethrow');
};
/**
* @ngdoc service
* @name ngMock.$log
*
* @description
* Mock implementation of {@link ng.$log} that gathers all logged messages in arrays
* (one array per logging level). These arrays are exposed as `logs` property of each of the
* level-specific log function, e.g. for level `error` the array is exposed as `$log.error.logs`.
*
*/
angular.mock.$LogProvider = function() {
function concat(array1, array2, index) {
return array1.concat(Array.prototype.slice.call(array2, index));
}
this.$get = function () {
var $log = {
log: function() { $log.log.logs.push(concat([], arguments, 0)); },
warn: function() { $log.warn.logs.push(concat([], arguments, 0)); },
info: function() { $log.info.logs.push(concat([], arguments, 0)); },
error: function() { $log.error.logs.push(concat([], arguments, 0)); }
};
/**
* @ngdoc method
* @name ngMock.$log#reset
* @methodOf ngMock.$log
*
* @description
* Reset all of the logging arrays to empty.
*/
$log.reset = function () {
/**
* @ngdoc property
* @name ngMock.$log#log.logs
* @propertyOf ngMock.$log
*
* @description
* Array of logged messages.
*/
$log.log.logs = [];
/**
* @ngdoc property
* @name ngMock.$log#warn.logs
* @propertyOf ngMock.$log
*
* @description
* Array of logged messages.
*/
$log.warn.logs = [];
/**
* @ngdoc property
* @name ngMock.$log#info.logs
* @propertyOf ngMock.$log
*
* @description
* Array of logged messages.
*/
$log.info.logs = [];
/**
* @ngdoc property
* @name ngMock.$log#error.logs
* @propertyOf ngMock.$log
*
* @description
* Array of logged messages.
*/
$log.error.logs = [];
};
/**
* @ngdoc method
* @name ngMock.$log#assertEmpty
* @methodOf ngMock.$log
*
* @description
* Assert that the all of the logging methods have no logged messages. If messages present, an exception is thrown.
*/
$log.assertEmpty = function() {
var errors = [];
angular.forEach(['error', 'warn', 'info', 'log'], function(logLevel) {
angular.forEach($log[logLevel].logs, function(log) {
angular.forEach(log, function (logItem) {
errors.push('MOCK $log (' + logLevel + '): ' + String(logItem) + '\n' + (logItem.stack || ''));
});
});
});
if (errors.length) {
errors.unshift("Expected $log to be empty! Either a message was logged unexpectedly, or an expected " +
"log message was not checked and removed:");
errors.push('');
throw new Error(errors.join('\n---------\n'));
}
};
$log.reset();
return $log;
};
};
(function() {
var R_ISO8061_STR = /^(\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?:\:?(\d\d)(?:\:?(\d\d)(?:\.(\d{3}))?)?)?(Z|([+-])(\d\d):?(\d\d)))?$/;
function jsonStringToDate(string){
var match;
if (match = string.match(R_ISO8061_STR)) {
var date = new Date(0),
tzHour = 0,
tzMin = 0;
if (match[9]) {
tzHour = int(match[9] + match[10]);
tzMin = int(match[9] + match[11]);
}
date.setUTCFullYear(int(match[1]), int(match[2]) - 1, int(match[3]));
date.setUTCHours(int(match[4]||0) - tzHour, int(match[5]||0) - tzMin, int(match[6]||0), int(match[7]||0));
return date;
}
return string;
}
function int(str) {
return parseInt(str, 10);
}
function padNumber(num, digits, trim) {
var neg = '';
if (num < 0) {
neg = '-';
num = -num;
}
num = '' + num;
while(num.length < digits) num = '0' + num;
if (trim)
num = num.substr(num.length - digits);
return neg + num;
}
/**
* @ngdoc object
* @name angular.mock.TzDate
* @description
*
* *NOTE*: this is not an injectable instance, just a globally available mock class of `Date`.
*
* Mock of the Date type which has its timezone specified via constroctor arg.
*
* The main purpose is to create Date-like instances with timezone fixed to the specified timezone
* offset, so that we can test code that depends on local timezone settings without dependency on
* the time zone settings of the machine where the code is running.
*
* @param {number} offset Offset of the *desired* timezone in hours (fractions will be honored)
* @param {(number|string)} timestamp Timestamp representing the desired time in *UTC*
*
* @example
* !!!! WARNING !!!!!
* This is not a complete Date object so only methods that were implemented can be called safely.
* To make matters worse, TzDate instances inherit stuff from Date via a prototype.
*
* We do our best to intercept calls to "unimplemented" methods, but since the list of methods is
* incomplete we might be missing some non-standard methods. This can result in errors like:
* "Date.prototype.foo called on incompatible Object".
*
* <pre>
* var newYearInBratislava = new TzDate(-1, '2009-12-31T23:00:00Z');
* newYearInBratislava.getTimezoneOffset() => -60;
* newYearInBratislava.getFullYear() => 2010;
* newYearInBratislava.getMonth() => 0;
* newYearInBratislava.getDate() => 1;
* newYearInBratislava.getHours() => 0;
* newYearInBratislava.getMinutes() => 0;
* </pre>
*
*/
angular.mock.TzDate = function (offset, timestamp) {
var self = new Date(0);
if (angular.isString(timestamp)) {
var tsStr = timestamp;
self.origDate = jsonStringToDate(timestamp);
timestamp = self.origDate.getTime();
if (isNaN(timestamp))
throw {
name: "Illegal Argument",
message: "Arg '" + tsStr + "' passed into TzDate constructor is not a valid date string"
};
} else {
self.origDate = new Date(timestamp);
}
var localOffset = new Date(timestamp).getTimezoneOffset();
self.offsetDiff = localOffset*60*1000 - offset*1000*60*60;
self.date = new Date(timestamp + self.offsetDiff);
self.getTime = function() {
return self.date.getTime() - self.offsetDiff;
};
self.toLocaleDateString = function() {
return self.date.toLocaleDateString();
};
self.getFullYear = function() {
return self.date.getFullYear();
};
self.getMonth = function() {
return self.date.getMonth();
};
self.getDate = function() {
return self.date.getDate();
};
self.getHours = function() {
return self.date.getHours();
};
self.getMinutes = function() {
return self.date.getMinutes();
};
self.getSeconds = function() {
return self.date.getSeconds();
};
self.getTimezoneOffset = function() {
return offset * 60;
};
self.getUTCFullYear = function() {
return self.origDate.getUTCFullYear();
};
self.getUTCMonth = function() {
return self.origDate.getUTCMonth();
};
self.getUTCDate = function() {
return self.origDate.getUTCDate();
};
self.getUTCHours = function() {
return self.origDate.getUTCHours();
};
self.getUTCMinutes = function() {
return self.origDate.getUTCMinutes();
};
self.getUTCSeconds = function() {
return self.origDate.getUTCSeconds();
};
self.getUTCMilliseconds = function() {
return self.origDate.getUTCMilliseconds();
};
self.getDay = function() {
return self.date.getDay();
};
// provide this method only on browsers that already have it
if (self.toISOString) {
self.toISOString = function() {
return padNumber(self.origDate.getUTCFullYear(), 4) + '-' +
padNumber(self.origDate.getUTCMonth() + 1, 2) + '-' +
padNumber(self.origDate.getUTCDate(), 2) + 'T' +
padNumber(self.origDate.getUTCHours(), 2) + ':' +
padNumber(self.origDate.getUTCMinutes(), 2) + ':' +
padNumber(self.origDate.getUTCSeconds(), 2) + '.' +
padNumber(self.origDate.getUTCMilliseconds(), 3) + 'Z'
}
}
//hide all methods not implemented in this mock that the Date prototype exposes
var unimplementedMethods = ['getMilliseconds', 'getUTCDay',
'getYear', 'setDate', 'setFullYear', 'setHours', 'setMilliseconds',
'setMinutes', 'setMonth', 'setSeconds', 'setTime', 'setUTCDate', 'setUTCFullYear',
'setUTCHours', 'setUTCMilliseconds', 'setUTCMinutes', 'setUTCMonth', 'setUTCSeconds',
'setYear', 'toDateString', 'toGMTString', 'toJSON', 'toLocaleFormat', 'toLocaleString',
'toLocaleTimeString', 'toSource', 'toString', 'toTimeString', 'toUTCString', 'valueOf'];
angular.forEach(unimplementedMethods, function(methodName) {
self[methodName] = function() {
throw Error("Method '" + methodName + "' is not implemented in the TzDate mock");
};
});
return self;
};
//make "tzDateInstance instanceof Date" return true
angular.mock.TzDate.prototype = Date.prototype;
})();
/**
* @ngdoc function
* @name angular.mock.debug
* @description
*
* *NOTE*: this is not an injectable instance, just a globally available function.
*
* Method for serializing common angular objects (scope, elements, etc..) into strings, useful for debugging.
*
* This method is also available on window, where it can be used to display objects on debug console.
*
* @param {*} object - any object to turn into string.
* @return {string} a serialized string of the argument
*/
angular.mock.dump = function(object) {
return serialize(object);
function serialize(object) {
var out;
if (angular.isElement(object)) {
object = angular.element(object);
out = angular.element('<div></div>');
angular.forEach(object, function(element) {
out.append(angular.element(element).clone());
});
out = out.html();
} else if (angular.isArray(object)) {
out = [];
angular.forEach(object, function(o) {
out.push(serialize(o));
});
out = '[ ' + out.join(', ') + ' ]';
} else if (angular.isObject(object)) {
if (angular.isFunction(object.$eval) && angular.isFunction(object.$apply)) {
out = serializeScope(object);
} else if (object instanceof Error) {
out = object.stack || ('' + object.name + ': ' + object.message);
} else {
out = angular.toJson(object, true);
}
} else {
out = String(object);
}
return out;
}
function serializeScope(scope, offset) {
offset = offset || ' ';
var log = [offset + 'Scope(' + scope.$id + '): {'];
for ( var key in scope ) {
if (scope.hasOwnProperty(key) && !key.match(/^(\$|this)/)) {
log.push(' ' + key + ': ' + angular.toJson(scope[key]));
}
}
var child = scope.$$childHead;
while(child) {
log.push(serializeScope(child, offset + ' '));
child = child.$$nextSibling;
}
log.push('}');
return log.join('\n' + offset);
}
};
/**
* @ngdoc object
* @name ngMock.$httpBackend
* @description
* Fake HTTP backend implementation suitable for unit testing application that use the
* {@link ng.$http $http service}.
*
* *Note*: For fake http backend implementation suitable for end-to-end testing or backend-less
* development please see {@link ngMockE2E.$httpBackend e2e $httpBackend mock}.
*
* During unit testing, we want our unit tests to run quickly and have no external dependencies so
* we don’t want to send {@link https://developer.mozilla.org/en/xmlhttprequest XHR} or
* {@link http://en.wikipedia.org/wiki/JSONP JSONP} requests to a real server. All we really need is
* to verify whether a certain request has been sent or not, or alternatively just let the
* application make requests, respond with pre-trained responses and assert that the end result is
* what we expect it to be.
*
* This mock implementation can be used to respond with static or dynamic responses via the
* `expect` and `when` apis and their shortcuts (`expectGET`, `whenPOST`, etc).
*
* When an Angular application needs some data from a server, it calls the $http service, which
* sends the request to a real server using $httpBackend service. With dependency injection, it is
* easy to inject $httpBackend mock (which has the same API as $httpBackend) and use it to verify
* the requests and respond with some testing data without sending a request to real server.
*
* There are two ways to specify what test data should be returned as http responses by the mock
* backend when the code under test makes http requests:
*
* - `$httpBackend.expect` - specifies a request expectation
* - `$httpBackend.when` - specifies a backend definition
*
*
* # Request Expectations vs Backend Definitions
*
* Request expectations provide a way to make assertions about requests made by the application and
* to define responses for those requests. The test will fail if the expected requests are not made
* or they are made in the wrong order.
*
* Backend definitions allow you to define a fake backend for your application which doesn't assert
* if a particular request was made or not, it just returns a trained response if a request is made.
* The test will pass whether or not the request gets made during testing.
*
*
* <table class="table">
* <tr><th width="220px"></th><th>Request expectations</th><th>Backend definitions</th></tr>
* <tr>
* <th>Syntax</th>
* <td>.expect(...).respond(...)</td>
* <td>.when(...).respond(...)</td>
* </tr>
* <tr>
* <th>Typical usage</th>
* <td>strict unit tests</td>
* <td>loose (black-box) unit testing</td>
* </tr>
* <tr>
* <th>Fulfills multiple requests</th>
* <td>NO</td>
* <td>YES</td>
* </tr>
* <tr>
* <th>Order of requests matters</th>
* <td>YES</td>
* <td>NO</td>
* </tr>
* <tr>
* <th>Request required</th>
* <td>YES</td>
* <td>NO</td>
* </tr>
* <tr>
* <th>Response required</th>
* <td>optional (see below)</td>
* <td>YES</td>
* </tr>
* </table>
*
* In cases where both backend definitions and request expectations are specified during unit
* testing, the request expectations are evaluated first.
*
* If a request expectation has no response specified, the algorithm will search your backend
* definitions for an appropriate response.
*
* If a request didn't match any expectation or if the expectation doesn't have the response
* defined, the backend definitions are evaluated in sequential order to see if any of them match
* the request. The response from the first matched definition is returned.
*
*
* # Flushing HTTP requests
*
* The $httpBackend used in production, always responds to requests with responses asynchronously.
* If we preserved this behavior in unit testing, we'd have to create async unit tests, which are
* hard to write, follow and maintain. At the same time the testing mock, can't respond
* synchronously because that would change the execution of the code under test. For this reason the
* mock $httpBackend has a `flush()` method, which allows the test to explicitly flush pending
* requests and thus preserving the async api of the backend, while allowing the test to execute
* synchronously.
*
*
* # Unit testing with mock $httpBackend
*
* <pre>
// controller
function MyController($scope, $http) {
$http.get('/auth.py').success(function(data) {
$scope.user = data;
});
this.saveMessage = function(message) {
$scope.status = 'Saving...';
$http.post('/add-msg.py', message).success(function(response) {
$scope.status = '';
}).error(function() {
$scope.status = 'ERROR!';
});
};
}
// testing controller
var $http;
beforeEach(inject(function($injector) {
$httpBackend = $injector.get('$httpBackend');
// backend definition common for all tests
$httpBackend.when('GET', '/auth.py').respond({userId: 'userX'}, {'A-Token': 'xxx'});
}));
afterEach(function() {
$httpBackend.verifyNoOutstandingExpectation();
$httpBackend.verifyNoOutstandingRequest();
});
it('should fetch authentication token', function() {
$httpBackend.expectGET('/auth.py');
var controller = scope.$new(MyController);
$httpBackend.flush();
});
it('should send msg to server', function() {
// now you don’t care about the authentication, but
// the controller will still send the request and
// $httpBackend will respond without you having to
// specify the expectation and response for this request
$httpBackend.expectPOST('/add-msg.py', 'message content').respond(201, '');
var controller = scope.$new(MyController);
$httpBackend.flush();
controller.saveMessage('message content');
expect(controller.status).toBe('Saving...');
$httpBackend.flush();
expect(controller.status).toBe('');
});
it('should send auth header', function() {
$httpBackend.expectPOST('/add-msg.py', undefined, function(headers) {
// check if the header was send, if it wasn't the expectation won't
// match the request and the test will fail
return headers['Authorization'] == 'xxx';
}).respond(201, '');
var controller = scope.$new(MyController);
controller.saveMessage('whatever');
$httpBackend.flush();
});
</pre>
*/
angular.mock.$HttpBackendProvider = function() {
this.$get = [createHttpBackendMock];
};
/**
* General factory function for $httpBackend mock.
* Returns instance for unit testing (when no arguments specified):
* - passing through is disabled
* - auto flushing is disabled
*
* Returns instance for e2e testing (when `$delegate` and `$browser` specified):
* - passing through (delegating request to real backend) is enabled
* - auto flushing is enabled
*
* @param {Object=} $delegate Real $httpBackend instance (allow passing through if specified)
* @param {Object=} $browser Auto-flushing enabled if specified
* @return {Object} Instance of $httpBackend mock
*/
function createHttpBackendMock($delegate, $browser) {
var definitions = [],
expectations = [],
responses = [],
responsesPush = angular.bind(responses, responses.push);
function createResponse(status, data, headers) {
if (angular.isFunction(status)) return status;
return function() {
return angular.isNumber(status)
? [status, data, headers]
: [200, status, data];
};
}
// TODO(vojta): change params to: method, url, data, headers, callback
function $httpBackend(method, url, data, callback, headers) {
var xhr = new MockXhr(),
expectation = expectations[0],
wasExpected = false;
function prettyPrint(data) {
return (angular.isString(data) || angular.isFunction(data) || data instanceof RegExp)
? data
: angular.toJson(data);
}
if (expectation && expectation.match(method, url)) {
if (!expectation.matchData(data))
throw Error('Expected ' + expectation + ' with different data\n' +
'EXPECTED: ' + prettyPrint(expectation.data) + '\nGOT: ' + data);
if (!expectation.matchHeaders(headers))
throw Error('Expected ' + expectation + ' with different headers\n' +
'EXPECTED: ' + prettyPrint(expectation.headers) + '\nGOT: ' +
prettyPrint(headers));
expectations.shift();
if (expectation.response) {
responses.push(function() {
var response = expectation.response(method, url, data, headers);
xhr.$$respHeaders = response[2];
callback(response[0], response[1], xhr.getAllResponseHeaders());
});
return;
}
wasExpected = true;
}
var i = -1, definition;
while ((definition = definitions[++i])) {
if (definition.match(method, url, data, headers || {})) {
if (definition.response) {
// if $browser specified, we do auto flush all requests
($browser ? $browser.defer : responsesPush)(function() {
var response = definition.response(method, url, data, headers);
xhr.$$respHeaders = response[2];
callback(response[0], response[1], xhr.getAllResponseHeaders());
});
} else if (definition.passThrough) {
$delegate(method, url, data, callback, headers);
} else throw Error('No response defined !');
return;
}
}
throw wasExpected ?
Error('No response defined !') :
Error('Unexpected request: ' + method + ' ' + url + '\n' +
(expectation ? 'Expected ' + expectation : 'No more request expected'));
}
/**
* @ngdoc method
* @name ngMock.$httpBackend#when
* @methodOf ngMock.$httpBackend
* @description
* Creates a new backend definition.
*
* @param {string} method HTTP method.
* @param {string|RegExp} url HTTP url.
* @param {(string|RegExp)=} data HTTP request body.
* @param {(Object|function(Object))=} headers HTTP headers or function that receives http header
* object and returns true if the headers match the current definition.
* @returns {requestHandler} Returns an object with `respond` method that control how a matched
* request is handled.
*
* - respond – `{function([status,] data[, headers])|function(function(method, url, data, headers)}`
* – The respond method takes a set of static data to be returned or a function that can return
* an array containing response status (number), response data (string) and response headers
* (Object).
*/
$httpBackend.when = function(method, url, data, headers) {
var definition = new MockHttpExpectation(method, url, data, headers),
chain = {
respond: function(status, data, headers) {
definition.response = createResponse(status, data, headers);
}
};
if ($browser) {
chain.passThrough = function() {
definition.passThrough = true;
};
}
definitions.push(definition);
return chain;
};
/**
* @ngdoc method
* @name ngMock.$httpBackend#whenGET
* @methodOf ngMock.$httpBackend
* @description
* Creates a new backend definition for GET requests. For more info see `when()`.
*
* @param {string|RegExp} url HTTP url.
* @param {(Object|function(Object))=} headers HTTP headers.
* @returns {requestHandler} Returns an object with `respond` method that control how a matched
* request is handled.
*/
/**
* @ngdoc method
* @name ngMock.$httpBackend#whenHEAD
* @methodOf ngMock.$httpBackend
* @description
* Creates a new backend definition for HEAD requests. For more info see `when()`.
*
* @param {string|RegExp} url HTTP url.
* @param {(Object|function(Object))=} headers HTTP headers.
* @returns {requestHandler} Returns an object with `respond` method that control how a matched
* request is handled.
*/
/**
* @ngdoc method
* @name ngMock.$httpBackend#whenDELETE
* @methodOf ngMock.$httpBackend
* @description
* Creates a new backend definition for DELETE requests. For more info see `when()`.
*
* @param {string|RegExp} url HTTP url.
* @param {(Object|function(Object))=} headers HTTP headers.
* @returns {requestHandler} Returns an object with `respond` method that control how a matched
* request is handled.
*/
/**
* @ngdoc method
* @name ngMock.$httpBackend#whenPOST
* @methodOf ngMock.$httpBackend
* @description
* Creates a new backend definition for POST requests. For more info see `when()`.
*
* @param {string|RegExp} url HTTP url.
* @param {(string|RegExp)=} data HTTP request body.
* @param {(Object|function(Object))=} headers HTTP headers.
* @returns {requestHandler} Returns an object with `respond` method that control how a matched
* request is handled.
*/
/**
* @ngdoc method
* @name ngMock.$httpBackend#whenPUT
* @methodOf ngMock.$httpBackend
* @description
* Creates a new backend definition for PUT requests. For more info see `when()`.
*
* @param {string|RegExp} url HTTP url.
* @param {(string|RegExp)=} data HTTP request body.
* @param {(Object|function(Object))=} headers HTTP headers.
* @returns {requestHandler} Returns an object with `respond` method that control how a matched
* request is handled.
*/
/**
* @ngdoc method
* @name ngMock.$httpBackend#whenJSONP
* @methodOf ngMock.$httpBackend
* @description
* Creates a new backend definition for JSONP requests. For more info see `when()`.
*
* @param {string|RegExp} url HTTP url.
* @returns {requestHandler} Returns an object with `respond` method that control how a matched
* request is handled.
*/
createShortMethods('when');
/**
* @ngdoc method
* @name ngMock.$httpBackend#expect
* @methodOf ngMock.$httpBackend
* @description
* Creates a new request expectation.
*
* @param {string} method HTTP method.
* @param {string|RegExp} url HTTP url.
* @param {(string|RegExp)=} data HTTP request body.
* @param {(Object|function(Object))=} headers HTTP headers or function that receives http header
* object and returns true if the headers match the current expectation.
* @returns {requestHandler} Returns an object with `respond` method that control how a matched
* request is handled.
*
* - respond – `{function([status,] data[, headers])|function(function(method, url, data, headers)}`
* – The respond method takes a set of static data to be returned or a function that can return
* an array containing response status (number), response data (string) and response headers
* (Object).
*/
$httpBackend.expect = function(method, url, data, headers) {
var expectation = new MockHttpExpectation(method, url, data, headers);
expectations.push(expectation);
return {
respond: function(status, data, headers) {
expectation.response = createResponse(status, data, headers);
}
};
};
/**
* @ngdoc method
* @name ngMock.$httpBackend#expectGET
* @methodOf ngMock.$httpBackend
* @description
* Creates a new request expectation for GET requests. For more info see `expect()`.
*
* @param {string|RegExp} url HTTP url.
* @param {Object=} headers HTTP headers.
* @returns {requestHandler} Returns an object with `respond` method that control how a matched
* request is handled. See #expect for more info.
*/
/**
* @ngdoc method
* @name ngMock.$httpBackend#expectHEAD
* @methodOf ngMock.$httpBackend
* @description
* Creates a new request expectation for HEAD requests. For more info see `expect()`.
*
* @param {string|RegExp} url HTTP url.
* @param {Object=} headers HTTP headers.
* @returns {requestHandler} Returns an object with `respond` method that control how a matched
* request is handled.
*/
/**
* @ngdoc method
* @name ngMock.$httpBackend#expectDELETE
* @methodOf ngMock.$httpBackend
* @description
* Creates a new request expectation for DELETE requests. For more info see `expect()`.
*
* @param {string|RegExp} url HTTP url.
* @param {Object=} headers HTTP headers.
* @returns {requestHandler} Returns an object with `respond` method that control how a matched
* request is handled.
*/
/**
* @ngdoc method
* @name ngMock.$httpBackend#expectPOST
* @methodOf ngMock.$httpBackend
* @description
* Creates a new request expectation for POST requests. For more info see `expect()`.
*
* @param {string|RegExp} url HTTP url.
* @param {(string|RegExp)=} data HTTP request body.
* @param {Object=} headers HTTP headers.
* @returns {requestHandler} Returns an object with `respond` method that control how a matched
* request is handled.
*/
/**
* @ngdoc method
* @name ngMock.$httpBackend#expectPUT
* @methodOf ngMock.$httpBackend
* @description
* Creates a new request expectation for PUT requests. For more info see `expect()`.
*
* @param {string|RegExp} url HTTP url.
* @param {(string|RegExp)=} data HTTP request body.
* @param {Object=} headers HTTP headers.
* @returns {requestHandler} Returns an object with `respond` method that control how a matched
* request is handled.
*/
/**
* @ngdoc method
* @name ngMock.$httpBackend#expectPATCH
* @methodOf ngMock.$httpBackend
* @description
* Creates a new request expectation for PATCH requests. For more info see `expect()`.
*
* @param {string|RegExp} url HTTP url.
* @param {(string|RegExp)=} data HTTP request body.
* @param {Object=} headers HTTP headers.
* @returns {requestHandler} Returns an object with `respond` method that control how a matched
* request is handled.
*/
/**
* @ngdoc method
* @name ngMock.$httpBackend#expectJSONP
* @methodOf ngMock.$httpBackend
* @description
* Creates a new request expectation for JSONP requests. For more info see `expect()`.
*
* @param {string|RegExp} url HTTP url.
* @returns {requestHandler} Returns an object with `respond` method that control how a matched
* request is handled.
*/
createShortMethods('expect');
/**
* @ngdoc method
* @name ngMock.$httpBackend#flush
* @methodOf ngMock.$httpBackend
* @description
* Flushes all pending requests using the trained responses.
*
* @param {number=} count Number of responses to flush (in the order they arrived). If undefined,
* all pending requests will be flushed. If there are no pending requests when the flush method
* is called an exception is thrown (as this typically a sign of programming error).
*/
$httpBackend.flush = function(count) {
if (!responses.length) throw Error('No pending request to flush !');
if (angular.isDefined(count)) {
while (count--) {
if (!responses.length) throw Error('No more pending request to flush !');
responses.shift()();
}
} else {
while (responses.length) {
responses.shift()();
}
}
$httpBackend.verifyNoOutstandingExpectation();
};
/**
* @ngdoc method
* @name ngMock.$httpBackend#verifyNoOutstandingExpectation
* @methodOf ngMock.$httpBackend
* @description
* Verifies that all of the requests defined via the `expect` api were made. If any of the
* requests were not made, verifyNoOutstandingExpectation throws an exception.
*
* Typically, you would call this method following each test case that asserts requests using an
* "afterEach" clause.
*
* <pre>
* afterEach($httpBackend.verifyExpectations);
* </pre>
*/
$httpBackend.verifyNoOutstandingExpectation = function() {
if (expectations.length) {
throw Error('Unsatisfied requests: ' + expectations.join(', '));
}
};
/**
* @ngdoc method
* @name ngMock.$httpBackend#verifyNoOutstandingRequest
* @methodOf ngMock.$httpBackend
* @description
* Verifies that there are no outstanding requests that need to be flushed.
*
* Typically, you would call this method following each test case that asserts requests using an
* "afterEach" clause.
*
* <pre>
* afterEach($httpBackend.verifyNoOutstandingRequest);
* </pre>
*/
$httpBackend.verifyNoOutstandingRequest = function() {
if (responses.length) {
throw Error('Unflushed requests: ' + responses.length);
}
};
/**
* @ngdoc method
* @name ngMock.$httpBackend#resetExpectations
* @methodOf ngMock.$httpBackend
* @description
* Resets all request expectations, but preserves all backend definitions. Typically, you would
* call resetExpectations during a multiple-phase test when you want to reuse the same instance of
* $httpBackend mock.
*/
$httpBackend.resetExpectations = function() {
expectations.length = 0;
responses.length = 0;
};
return $httpBackend;
function createShortMethods(prefix) {
angular.forEach(['GET', 'DELETE', 'JSONP'], function(method) {
$httpBackend[prefix + method] = function(url, headers) {
return $httpBackend[prefix](method, url, undefined, headers)
}
});
angular.forEach(['PUT', 'POST', 'PATCH'], function(method) {
$httpBackend[prefix + method] = function(url, data, headers) {
return $httpBackend[prefix](method, url, data, headers)
}
});
}
}
function MockHttpExpectation(method, url, data, headers) {
this.data = data;
this.headers = headers;
this.match = function(m, u, d, h) {
if (method != m) return false;
if (!this.matchUrl(u)) return false;
if (angular.isDefined(d) && !this.matchData(d)) return false;
if (angular.isDefined(h) && !this.matchHeaders(h)) return false;
return true;
};
this.matchUrl = function(u) {
if (!url) return true;
if (angular.isFunction(url.test)) return url.test(u);
return url == u;
};
this.matchHeaders = function(h) {
if (angular.isUndefined(headers)) return true;
if (angular.isFunction(headers)) return headers(h);
return angular.equals(headers, h);
};
this.matchData = function(d) {
if (angular.isUndefined(data)) return true;
if (data && angular.isFunction(data.test)) return data.test(d);
if (data && !angular.isString(data)) return angular.toJson(data) == d;
return data == d;
};
this.toString = function() {
return method + ' ' + url;
};
}
function MockXhr() {
// hack for testing $http, $httpBackend
MockXhr.$$lastInstance = this;
this.open = function(method, url, async) {
this.$$method = method;
this.$$url = url;
this.$$async = async;
this.$$reqHeaders = {};
this.$$respHeaders = {};
};
this.send = function(data) {
this.$$data = data;
};
this.setRequestHeader = function(key, value) {
this.$$reqHeaders[key] = value;
};
this.getResponseHeader = function(name) {
// the lookup must be case insensitive, that's why we try two quick lookups and full scan at last
var header = this.$$respHeaders[name];
if (header) return header;
name = angular.lowercase(name);
header = this.$$respHeaders[name];
if (header) return header;
header = undefined;
angular.forEach(this.$$respHeaders, function(headerVal, headerName) {
if (!header && angular.lowercase(headerName) == name) header = headerVal;
});
return header;
};
this.getAllResponseHeaders = function() {
var lines = [];
angular.forEach(this.$$respHeaders, function(value, key) {
lines.push(key + ': ' + value);
});
return lines.join('\n');
};
this.abort = angular.noop;
}
/**
* @ngdoc function
* @name ngMock.$timeout
* @description
*
* This service is just a simple decorator for {@link ng.$timeout $timeout} service
* that adds a "flush" method.
*/
/**
* @ngdoc method
* @name ngMock.$timeout#flush
* @methodOf ngMock.$timeout
* @description
*
* Flushes the queue of pending tasks.
*/
/**
*
*/
angular.mock.$RootElementProvider = function() {
this.$get = function() {
return angular.element('<div ng-app></div>');
}
};
/**
* @ngdoc overview
* @name ngMock
* @description
*
* The `ngMock` is an angular module which is used with `ng` module and adds unit-test configuration as well as useful
* mocks to the {@link AUTO.$injector $injector}.
*/
angular.module('ngMock', ['ng']).provider({
$browser: angular.mock.$BrowserProvider,
$exceptionHandler: angular.mock.$ExceptionHandlerProvider,
$log: angular.mock.$LogProvider,
$httpBackend: angular.mock.$HttpBackendProvider,
$rootElement: angular.mock.$RootElementProvider
}).config(function($provide) {
$provide.decorator('$timeout', function($delegate, $browser) {
$delegate.flush = function() {
$browser.defer.flush();
};
return $delegate;
});
});
/**
* @ngdoc overview
* @name ngMockE2E
* @description
*
* The `ngMockE2E` is an angular module which contains mocks suitable for end-to-end testing.
* Currently there is only one mock present in this module -
* the {@link ngMockE2E.$httpBackend e2e $httpBackend} mock.
*/
angular.module('ngMockE2E', ['ng']).config(function($provide) {
$provide.decorator('$httpBackend', angular.mock.e2e.$httpBackendDecorator);
});
/**
* @ngdoc object
* @name ngMockE2E.$httpBackend
* @description
* Fake HTTP backend implementation suitable for end-to-end testing or backend-less development of
* applications that use the {@link ng.$http $http service}.
*
* *Note*: For fake http backend implementation suitable for unit testing please see
* {@link ngMock.$httpBackend unit-testing $httpBackend mock}.
*
* This implementation can be used to respond with static or dynamic responses via the `when` api
* and its shortcuts (`whenGET`, `whenPOST`, etc) and optionally pass through requests to the
* real $httpBackend for specific requests (e.g. to interact with certain remote apis or to fetch
* templates from a webserver).
*
* As opposed to unit-testing, in an end-to-end testing scenario or in scenario when an application
* is being developed with the real backend api replaced with a mock, it is often desirable for
* certain category of requests to bypass the mock and issue a real http request (e.g. to fetch
* templates or static files from the webserver). To configure the backend with this behavior
* use the `passThrough` request handler of `when` instead of `respond`.
*
* Additionally, we don't want to manually have to flush mocked out requests like we do during unit
* testing. For this reason the e2e $httpBackend automatically flushes mocked out requests
* automatically, closely simulating the behavior of the XMLHttpRequest object.
*
* To setup the application to run with this http backend, you have to create a module that depends
* on the `ngMockE2E` and your application modules and defines the fake backend:
*
* <pre>
* myAppDev = angular.module('myAppDev', ['myApp', 'ngMockE2E']);
* myAppDev.run(function($httpBackend) {
* phones = [{name: 'phone1'}, {name: 'phone2'}];
*
* // returns the current list of phones
* $httpBackend.whenGET('/phones').respond(phones);
*
* // adds a new phone to the phones array
* $httpBackend.whenPOST('/phones').respond(function(method, url, data) {
* phones.push(angular.fromJSON(data));
* });
* $httpBackend.whenGET(/^\/templates\//).passThrough();
* //...
* });
* </pre>
*
* Afterwards, bootstrap your app with this new module.
*/
/**
* @ngdoc method
* @name ngMockE2E.$httpBackend#when
* @methodOf ngMockE2E.$httpBackend
* @description
* Creates a new backend definition.
*
* @param {string} method HTTP method.
* @param {string|RegExp} url HTTP url.
* @param {(string|RegExp)=} data HTTP request body.
* @param {(Object|function(Object))=} headers HTTP headers or function that receives http header
* object and returns true if the headers match the current definition.
* @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that
* control how a matched request is handled.
*
* - respond – `{function([status,] data[, headers])|function(function(method, url, data, headers)}`
* – The respond method takes a set of static data to be returned or a function that can return
* an array containing response status (number), response data (string) and response headers
* (Object).
* - passThrough – `{function()}` – Any request matching a backend definition with `passThrough`
* handler, will be pass through to the real backend (an XHR request will be made to the
* server.
*/
/**
* @ngdoc method
* @name ngMockE2E.$httpBackend#whenGET
* @methodOf ngMockE2E.$httpBackend
* @description
* Creates a new backend definition for GET requests. For more info see `when()`.
*
* @param {string|RegExp} url HTTP url.
* @param {(Object|function(Object))=} headers HTTP headers.
* @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that
* control how a matched request is handled.
*/
/**
* @ngdoc method
* @name ngMockE2E.$httpBackend#whenHEAD
* @methodOf ngMockE2E.$httpBackend
* @description
* Creates a new backend definition for HEAD requests. For more info see `when()`.
*
* @param {string|RegExp} url HTTP url.
* @param {(Object|function(Object))=} headers HTTP headers.
* @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that
* control how a matched request is handled.
*/
/**
* @ngdoc method
* @name ngMockE2E.$httpBackend#whenDELETE
* @methodOf ngMockE2E.$httpBackend
* @description
* Creates a new backend definition for DELETE requests. For more info see `when()`.
*
* @param {string|RegExp} url HTTP url.
* @param {(Object|function(Object))=} headers HTTP headers.
* @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that
* control how a matched request is handled.
*/
/**
* @ngdoc method
* @name ngMockE2E.$httpBackend#whenPOST
* @methodOf ngMockE2E.$httpBackend
* @description
* Creates a new backend definition for POST requests. For more info see `when()`.
*
* @param {string|RegExp} url HTTP url.
* @param {(string|RegExp)=} data HTTP request body.
* @param {(Object|function(Object))=} headers HTTP headers.
* @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that
* control how a matched request is handled.
*/
/**
* @ngdoc method
* @name ngMockE2E.$httpBackend#whenPUT
* @methodOf ngMockE2E.$httpBackend
* @description
* Creates a new backend definition for PUT requests. For more info see `when()`.
*
* @param {string|RegExp} url HTTP url.
* @param {(string|RegExp)=} data HTTP request body.
* @param {(Object|function(Object))=} headers HTTP headers.
* @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that
* control how a matched request is handled.
*/
/**
* @ngdoc method
* @name ngMockE2E.$httpBackend#whenPATCH
* @methodOf ngMockE2E.$httpBackend
* @description
* Creates a new backend definition for PATCH requests. For more info see `when()`.
*
* @param {string|RegExp} url HTTP url.
* @param {(string|RegExp)=} data HTTP request body.
* @param {(Object|function(Object))=} headers HTTP headers.
* @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that
* control how a matched request is handled.
*/
/**
* @ngdoc method
* @name ngMockE2E.$httpBackend#whenJSONP
* @methodOf ngMockE2E.$httpBackend
* @description
* Creates a new backend definition for JSONP requests. For more info see `when()`.
*
* @param {string|RegExp} url HTTP url.
* @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that
* control how a matched request is handled.
*/
angular.mock.e2e = {};
angular.mock.e2e.$httpBackendDecorator = ['$delegate', '$browser', createHttpBackendMock];
angular.mock.clearDataCache = function() {
var key,
cache = angular.element.cache;
for(key in cache) {
if (cache.hasOwnProperty(key)) {
var handle = cache[key].handle;
handle && angular.element(handle.elem).unbind();
delete cache[key];
}
}
};
window.jstestdriver && (function(window) {
/**
* Global method to output any number of objects into JSTD console. Useful for debugging.
*/
window.dump = function() {
var args = [];
angular.forEach(arguments, function(arg) {
args.push(angular.mock.dump(arg));
});
jstestdriver.console.log.apply(jstestdriver.console, args);
if (window.console) {
window.console.log.apply(window.console, args);
}
};
})(window);
(window.jasmine || window.mocha) && (function(window) {
var currentSpec = null;
beforeEach(function() {
currentSpec = this;
});
afterEach(function() {
var injector = currentSpec.$injector;
currentSpec.$injector = null;
currentSpec.$modules = null;
currentSpec = null;
if (injector) {
injector.get('$rootElement').unbind();
injector.get('$browser').pollFns.length = 0;
}
angular.mock.clearDataCache();
// clean up jquery's fragment cache
angular.forEach(angular.element.fragments, function(val, key) {
delete angular.element.fragments[key];
});
MockXhr.$$lastInstance = null;
angular.forEach(angular.callbacks, function(val, key) {
delete angular.callbacks[key];
});
angular.callbacks.counter = 0;
});
function isSpecRunning() {
return currentSpec && currentSpec.queue.running;
}
/**
* @ngdoc function
* @name angular.mock.module
* @description
*
* *NOTE*: This is function is also published on window for easy access.<br>
* *NOTE*: Only available with {@link http://pivotal.github.com/jasmine/ jasmine}.
*
* This function registers a module configuration code. It collects the configuration information
* which will be used when the injector is created by {@link angular.mock.inject inject}.
*
* See {@link angular.mock.inject inject} for usage example
*
* @param {...(string|Function)} fns any number of modules which are represented as string
* aliases or as anonymous module initialization functions. The modules are used to
* configure the injector. The 'ng' and 'ngMock' modules are automatically loaded.
*/
window.module = angular.mock.module = function() {
var moduleFns = Array.prototype.slice.call(arguments, 0);
return isSpecRunning() ? workFn() : workFn;
/////////////////////
function workFn() {
if (currentSpec.$injector) {
throw Error('Injector already created, can not register a module!');
} else {
var modules = currentSpec.$modules || (currentSpec.$modules = []);
angular.forEach(moduleFns, function(module) {
modules.push(module);
});
}
}
};
/**
* @ngdoc function
* @name angular.mock.inject
* @description
*
* *NOTE*: This is function is also published on window for easy access.<br>
* *NOTE*: Only available with {@link http://pivotal.github.com/jasmine/ jasmine}.
*
* The inject function wraps a function into an injectable function. The inject() creates new
* instance of {@link AUTO.$injector $injector} per test, which is then used for
* resolving references.
*
* See also {@link angular.mock.module module}
*
* Example of what a typical jasmine tests looks like with the inject method.
* <pre>
*
* angular.module('myApplicationModule', [])
* .value('mode', 'app')
* .value('version', 'v1.0.1');
*
*
* describe('MyApp', function() {
*
* // You need to load modules that you want to test,
* // it loads only the "ng" module by default.
* beforeEach(module('myApplicationModule'));
*
*
* // inject() is used to inject arguments of all given functions
* it('should provide a version', inject(function(mode, version) {
* expect(version).toEqual('v1.0.1');
* expect(mode).toEqual('app');
* }));
*
*
* // The inject and module method can also be used inside of the it or beforeEach
* it('should override a version and test the new version is injected', function() {
* // module() takes functions or strings (module aliases)
* module(function($provide) {
* $provide.value('version', 'overridden'); // override version here
* });
*
* inject(function(version) {
* expect(version).toEqual('overridden');
* });
* ));
* });
*
* </pre>
*
* @param {...Function} fns any number of functions which will be injected using the injector.
*/
window.inject = angular.mock.inject = function() {
var blockFns = Array.prototype.slice.call(arguments, 0);
var errorForStack = new Error('Declaration Location');
return isSpecRunning() ? workFn() : workFn;
/////////////////////
function workFn() {
var modules = currentSpec.$modules || [];
modules.unshift('ngMock');
modules.unshift('ng');
var injector = currentSpec.$injector;
if (!injector) {
injector = currentSpec.$injector = angular.injector(modules);
}
for(var i = 0, ii = blockFns.length; i < ii; i++) {
try {
injector.invoke(blockFns[i] || angular.noop, this);
} catch (e) {
if(e.stack) e.stack += '\n' + errorForStack.stack;
throw e;
} finally {
errorForStack = null;
}
}
}
};
})(window);