Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

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

I use the $http service.

like image 327
Kenneth Lynne Avatar asked Dec 03 '13 12:12

Kenneth Lynne


1 Answers

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.

Example:

    //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, messages.data, {/*headers*/}];
    });

    $httpBackend.whenPOST(APIBase + 'messages').respond(function(method, url, data, headers) {
        var message = angular.fromJson(data);

        messages.data.push(message);
        //You should consider having the back-end being responsible for creating new id tho!
        messages.index[message.id] = 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())

like image 183
Kenneth Lynne Avatar answered Nov 08 '22 18:11

Kenneth Lynne