Skip to content

Instantly share code, notes, and snippets.

@richardm
Created February 26, 2014 20:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save richardm/9237731 to your computer and use it in GitHub Desktop.
Save richardm/9237731 to your computer and use it in GitHub Desktop.
Using $httpBackend to develop an AngularJS frontend using test data before the backend is ready. Be sure to include jSendHttp, angular-sanitize.js, and angular-mocks.js.
angular
.module('API', ['testData']) // Remove testData to make real http request
.factory('UsersAPI', function ($http, $q, $jSendHttp) {
return {
getUsers: function (companyId) {
return $jSendHttp.get('/api/UsersController/getUsers?companyId=' + companyId);
}
};
});
angular
.module('users', ['API'])
.controller('Users_MainCtrl', function ($scope, UsersAPI) {
var companyId = 123; // get from url, etc.
$scope.users = {};
$scope.usersLoaded = false;
UsersAPI.getUsers(companyId).then(function (data) {
$scope.users = data;
$scope.usersLoaded = true;
});
});
<div ng-controller="Users_MainCtrl">
<div ng-if="usersLoaded">
<h1>Users</h1>
<ul>
<li ng-repeat="user in users">{{ user.id }} - {{ user.name }}</li>
</ul>
</div>
</div>
// This module will intercept http requests and return test data
angular
.module('testData', ['ngMockE2E'])
.run(function ($httpBackend, UserData) {
function wrapWithJSend (data) {
return [
200,
{
"status": "success",
"message": "OK",
"code": 0,
"data": data
}
];
}
// Add route for each url you want to intercept
// Can use regex to capture parameters and return different test data for different values
var routes = {
'GET': {
'getUsers': {
regex: /\/api\/UsersController\/getUsers\?companyId=(\d+)$/,
cb: function (url) {
var companyId = url.match(/(\d+)$/)[0];
return UserData.getUsers(companyId);
}
}
}
}
angular.forEach(routes['GET'], function (item, key) {
$httpBackend.whenGET(item['regex']).respond(function (method, url, data, header) {
console.log('USING TEST DATA FOR ' + url);
return wrapWithJSend(item['cb'](url));
});
});
// For everything else, don't mock
$httpBackend.whenGET(/\/*/).passThrough();
$httpBackend.whenPOST(/\/*/).passThrough();
})
.factory('UserData', function () {
var company1Users = [
{
id: 142,
name: 'Richard'
},
{
id: 234,
name: 'John'
}
];
var company2Users = [
{
id: 142,
name: 'Mike'
},
{
id: 234,
name: 'Jason'
}
];
return {
getUsers: function (companyId) {
if (companyId == 1) {
return company1Users;
} else {
return company2Users;
}
}
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment