using mock httpbackend
test UI without need for backend
HTML
<script src="http://code.angularjs.org/1.1.1/angular-mocks.js"></script>
<body >
<h4>Http backend mocking. See <a target="_blank" href="http://www.opensourceconnections.com/2013/09/14/angularjs-completely-mocking-your-backend">this blog post</a></h4>
<div ng-app="myApp">
<span ng-controller="UserCtrl">
<ul>
<li ng-repeat="user in users">{{user.userId}}: {{user.userName}}</li>
<button ng-click="addUser()">Add user (HTTP PUT)</button>
</ul>
</span>
</div>
</body>
JavaScript
'use strict';
// *************************************************
// MOCK BACKEND
var myApp = angular.module('myApp', []);
// You can also just use provide to blanket replace $httpBackend
// with the mock
myApp
.config(function($provide) {
// Decorate by passing in the constructor for mock $httpBackend
$provide.decorator('$httpBackend', createHttpBackendMock);
});
// Mark urls that match regexp as a match,
// you can pass this as the url argument to $httpBackend.[when|expect]
angular.module('myApp')
.run(function($httpBackend, $timeout) {
var regexpUrl = function(regexp) {
return {
test: function(url) {
this.matches = url.match(regexp);
return this.matches && this.matches.length > 0;
}
};
};
//*******************************************
// Allow JSONP to pass to external services (ie Solr)
$httpBackend.when('JSONP', regexpUrl(/http:\/\/.*/)).passThrough();
// Some statefullness
var users = {};
var userId = 0;
$httpBackend.when('PUT', '/users')
.respond(function(method, url, data) {
data = angular.fromJson(data);
users[userId] = {userName: data.userName, userId: userId};
userId++;
return [200, users[data.userId]];
});
$httpBackend.when('GET', regexpUrl(/users\/(\d+)/))
.respond(function(method, url, data) {
data = angular.fromJson(data);
return [200, users[data.userId]];
});
$httpBackend.when('GET', '/users')
.respond(function(method, url, data) {
return [200, users];
});
// A "run loop" of sorts to get httpBackend to
// issue responses and trigger the client code's callbacks
var flushBackend = function() {
try {
$httpBackend.flush();
} catch (err) {
// ignore that there's nothing to flush
}
$timeout(flushBackend, 500);
};
$timeout(flushBackend, 500);
});
// *************************************************
// *************************************************
// ACTUAL APP
// An actual angular app you might...