Use Angular mock to load JSON file for Backendless development Use Angular mock to load JSON file for Backendless development ajax ajax

Use Angular mock to load JSON file for Backendless development


Following worked for me without any hack

$httpBackend.whenGET('/endpoint').respond($resource("/path/to.json").query());

Courtesy https://groups.google.com/d/msg/angular/grbwk-VehDE/UBIho6qcmLMJ


A very clean solution to this problem is to work with plain vanilla JavaScript since $httpBackend is not made to handle asynchronous requests.

This method doesn't require jQuery code.

$httpBackend.when('GET', 'http://localhost:3000/api/data').respond(getData());function getData() {               var request = new XMLHttpRequest();               request.open('GET', '/db/myData.json', false);               request.send(null);               return [request.status, request.response, {}];}

I got this tip from:https://stackoverflow.com/a/24287558/4742733


I know it's a late response but will share my experience hoping to be of some help for future peers.

I successfully achieved a working mocked backend thanks to this extremely useful blog post.

First of all I put all my endpoints in one place as constants in order to define them only once and have them available in the mocked backend, in my tests and obviously in all the services responsible of AJAX calls.

angular.module('appName.urls', []) .constant('API_endpoints', {   login: 'authentication/login',   logout: 'authentication/logout',   signUp: 'authentication/signup',   userList: 'users/list' });

I then added ngMockE2E as a dependency to the whole app.

angular.module('appName', [  'ui.router',   ...   'ngMockE2E'])

Then I created a file for the actual mocked backend, let's call it fakeBackend.js and referenced in the index.html. This file was taken from the above link, but here's a simplified example from my implementation (here serving an emulated login):

angular.module('appName').run(function($httpBackend, API_endpoints) {   var credentials = {    email : 'a@a.a',    password : '12345'  };  $httpBackend.whenPOST(API_endpoints.login)              .respond(function(method, url, data) {    var req = JSON.parse(data),        res;    // very light credential check...    if(req.email === credentials.email && req.password === credentials.password ){        // generate a successful response        res = [200, {uuid:1}, {}];    } else {        // generate an error if credentials are wrong        res = [400, {}, {}];    }    return res;  });   // Respond to all templates request   // Every file in states/ folder will be served automatically   $httpBackend.whenGET(/states\//).passThrough();}):

Note also the last line that serves all the content from my states folder, where all my templates reside. This is obviously a very simplistic example, but the blog post author also shared a very detailed and useful plunkr.