Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

does anyone has an example using $httpBackend (service in module ngMockE2E )

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!

like image 961
Or A Avatar asked Feb 19 '13 04:02

Or A


2 Answers

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:

  1. Referenced the angular-mocks.js file in the html.
  2. Added ngMockE2E in the angular.module requires array on line 3 in app.js
  3. Injected $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.

like image 112
Gloopy Avatar answered Oct 25 '22 09:10

Gloopy


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);
like image 22
Nash Worth Avatar answered Oct 25 '22 11:10

Nash Worth