I'm really looking to find the simplest way to get my angular app to use a mock backend service.
any pointers would be great, a sample app that show how to write a simple app the use it would do the job. tnx!
Here is a sample plunkr using the $httpBackend for a sample with backend-less development as an example to answer this question.
The main things I added to the plnkr to get this to work are:
angular-mocks.js file in the html.ngMockE2E in the angular.module requires array on line 3 in app.js$httpBackend to the app.run and added code to tell the mock backend what to respond with when a GET to a specific URL is requested.This was mostly taken from the $httpBackend documentation. Note you can do a .passThrough() for any calls where you want to actually hit the backend (bypassing the mock). This is especially useful if portions of the backend are already working.
Here is a basic template pulled from various examples:
'use strict';
(function() {
    if( !document.URL.match(/\?nobackend$/) ){
        // if not requested only add a blank stub to app dependency.
        angular.module('ds.backendMock', []);
    } else if (document.URL.match(/\?nobackend$/)) {
        // if the query string is present add a module with a run definition to replace the back end.
        angular.module('myMock', ['ngMockE2E'])
            .run(function($httpBackend) {
                // MOCK-RUNNER-CONFIGURATION-.
                var DOMAIN = 'example.com',
        $httpBackend.whenGET('http://'+DOMAIN+'/someexample')
                    .respond(
                        //MOCK-ERROR-STATUS-CODE
                        //401 //500 //404  //uncomment integer to mock status code and comment out mock data.
                        //MOCK-DATA-RESPONSE
                        {
                          'id' : '1',
                          'name' : 'MOCK',
                          'description' : 'mocking',
                        }
                    ); //end mock.
                    // various passthroughs. these allow existing services to work, while some are mocked.
                    $httpBackend.whenGET('./some.html').passThrough();
                    // dont mock everything else, specify pass through to avoid error.
                    $httpBackend.whenGET(/^\w+.*/).passThrough();
                    $httpBackend.whenPOST(/^\w+.*/).passThrough();
                });
        }
})(angular);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With