AngularJS fake $ httpBackend.whenPOST () Uncaught TypeError: Cannot read property '2' from undefined

Pretty new to AngularJS and got a $ httpBackend layout that works as described in the docs (see here: http://docs.angularjs.org/api/ngMockE2E.$httpBackend). I can reproduce the GET code, for example:

$httpBackend.whenGET('/phones').respond(phones); 

The POST method, however, fails with the angular -mocks.js error. This is what I point to in POST:

  $httpBackend.whenPOST('/phones').respond(function(method,url,data){ console.log(data); phones.push(angular.fromJson(data)); }); 

This is how I call POST from the controller:

  var newPhone = {name:'New Phone'}; $http.post('/forecasts/types.json', newPhone); 

And here is what I see in the console in response:

 {"name":"New Phone"} app.js:167 Uncaught TypeError: Cannot read property '2' of undefined angular-mocks.js:876 (anonymous function) angular-mocks.js:876 completeOutstandingRequest angular.js:2930 (anonymous function) angular.js:3209 

My code looks about the same as documents. The function is called when POSTed is sent, but I cannot understand why it will not work.

Edit (thanks to Josh David Miller for his comment again for the fiddle) Here is a fiddle that reproduces the error: http://jsfiddle.net/elcabo/btbds/3/ The fiddle is based on an example in Angular docs (http: //docs.angularjs. org / api / ngMockE2E. $ httpBackend) and Angular script for mockE2E $ httpBackend (http://jsfiddle.net/vojtajina/DQHdk/)

Has anyone come across this before or had any ideas on how to attack this?

I searched fairly broadly for solution / relevant posts, but can't find, so any pointers would be very appreciated.

Many thanks.

+8
angularjs
source share
1 answer

I updated your jsFiddle, which now works: http://jsfiddle.net/joshdmiller/EgMpe/ .

Firstly, the version of AngularJS was unusually old. I updated it from 0.10.6 to 1.0.3. With this change, many syntax changes have appeared that you can find in the fiddle.

But the problem you ran into was that you did not return the value in your $httpBackend.whenPOST method. The respond method is respond return a value indicating the status, response body, and headers. The verbal example that I included in the working script is as follows:

 $httpBackend.whenPOST('/phones').respond(function(method, url, data, headers){ console.log('Received these data:', method, url, data, headers); phones.push(angular.fromJson(data)); return [200, {}, {}]; }); 

The returned array is the response status 200 , an empty response body, and an empty set of headers (i.e. using default values).

I also added whenGET so you can see them together:

 $httpBackend.whenGET('/phones').respond(function(method,url,data) { console.log("Getting phones"); return [200, phones, {}]; }); 
+14
source

All Articles