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

12.5k views Asked by At

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.

5

There are 5 answers

3
Kenneth Lynne On BEST ANSWER

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())

0
Mahbub On

What I do these days is through apiary.io, it's free. You can write your API endpoints as a blueprint and just request them just like you'd request a REST Server. You can also write whatever response you want to serve. Useful when the REST server is not ready but your Front End is.

1
pasine On

You can use $httpBackend

Here's an example from the AngularJS website:

phones = [{name: 'phone1'}, {name: 'phone2'}];


// returns the current list of phones
$httpBackend.whenGET('/phones').respond(phones);
0
Remco Vlierman On

Just to add to these answers: take a look at https://github.com/mdasberg/ng-apimock

and https://www.npmjs.com/package/open-api-test-generator

ng-apimock is a scenario switcher for protractor and development, and open-api-test-generator can generate mocks for this tool. Pretty handy stuff once you get to know the modules

0
Bulki S Maslom On

For an alternative more automated way of backend mocking, take a look at swagger-api-mock that works just great together with rest-json. These modules together can be used to generate $httpBackend responses: rest-json.js as http-like access to json data and swagger-api-mock/lib/mock-data.js as generator for the json mock data objects based on swagger (or json schema) definitions