Use Angular mock to load JSON file for Backendless development
ajax, angular-mock, angularjs, javascript, json
Solution
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
Problem
I wrote this little code in separate .js file for frontend backendless environment. I need to get `myfile.json` whenever there is an ajax calling `/somelink`. ``` angular.module('myApp') .config(function($provide) { $provide.decorator('$httpBackend', angular.mock.e2e.$httpBackendDecorator); }) .run(function($httpBackend, $http) { $httpBackend.whenGET('/somelink').respond(function(method, url, data) { $http({method: 'GET', url: '/somelink/myfile.json'}) .success(function(data, status, headers, config) { return data; }) .error(function(data, status, headers, config) { }); }); }); ``` However this code doesn't work and gave me error: ``` Error: Unexpected request: GET /somelink/myfile.json ``` Can someone help me fix this? Note that I don't want to call $http directly to get .json file inside my code because that will trash the production code. The purpose of doing this is to keep this code for backendless development separately. Thanks. UPDATE 1: I added: ``` $rootScope.$apply(); $httpBackend.flush(); ``` Now I have another error in addition to same one previously: `Uncaught Error: No pending request to flush !` UPDATE 2: After playing around, I found a small hack. I put this in `.run()` before all other $httpBackend mocks. Also this `.js` file must be placed before all controllers/services/directives and after the app.js bootstrap. ``` var data; $.ajax({ type: 'GET', async: false, url: '/somelink/myfile.json' }).success(function(res) { data = res; }).error(function(data) { }); ``` Then this: ``` $httpBackend.whenGET('/somelink').respond(data); ``` The key is `async: false` so that this makes sure the JSON is loaded into variable `data`. All of these must happen before other objects triggered and call ajax events. This is a hack for frontend backendless development only. When production, of course this .js file is removed. I don't like this much is because using `async: false` and direct `$.ajax()` instead of `$http`