Kenneth Lynne Kenneth Lynne - 1 year ago 70
AngularJS Question

How can I create a mock back-end in Angular?

How can I implement a mock back-end to do quick prototyping with Angular?

I need to be able to fake response delay, response data and the like.

I use the $http service.

Answer Source

You can use angular mocks to provide a mock back-end.

Working demo on plnkr.

Basically you include angular-mocks after angular, and use the code provided in this gist and you will be able to control both requests and responses, including headers and fake response delays etc.


    //When backend receives a request to the views folder, pass it through
    $httpBackend.whenGET( RegExp( regEsc( Config.view_dir ) ) ).passThrough(); 

    //Message should return a list og messages
    $httpBackend.whenGET(APIBase + 'messages').respond(function(method, url, data, headers) {
        return [200,, {/*headers*/}];

    $httpBackend.whenPOST(APIBase + 'messages').respond(function(method, url, data, headers) {
        var message = angular.fromJson(data);;
        //You should consider having the back-end being responsible for creating new id tho!
        messages.index[] = message; 

        return [200, message, {/*headers*/}];

    //Message/id should return a message
    $httpBackend.whenGET( RegExp(regEsc(APIBase + 'messages') + '\d+$') ).respond(function(method, url, data, headers) {
        var id = url.match(/\d+$/)[0];
        return [200, messages.index[id] || null, {/*headers*/}];


You can also set up urls that should pass trough to a actual server too (check passThrough())

I will provide a decent jsfiddle later on!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download