Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

angularjs

Pretty new to AngularJS and got a mock $httpBackend working as described in the docs (see here:http://docs.angularjs.org/api/ngMockE2E.$httpBackend). I can reproduce the GET code e.g.:

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

The POST, method, however, fails with an angular-mocks.js error. This is what I specify to happen on POST:

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

This is how I call the POST from the controller:

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

And this 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 pretty much the same as the docs. The function is called when POSTed to but I can't figure out why it won't run.

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

Has anyone encountered this before or have any ideas on how to attack this?

I've searched pretty wide for a solution/relevant posts but can't find any, so any pointers would be greatly appreciated.

Many thanks.

like image 242
coderigo Avatar asked Jan 10 '13 12:01

coderigo


1 Answers

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

First, the version of AngularJS was extraordinarily old. I updated it from 0.10.6 to 1.0.3. With that change came many syntactic changes, which you can find in the fiddle.

But the issue you were having was from not returning a value in your $httpBackend.whenPOST method. The respond method is expected to return a value indicating the status, response body, and headers. The verbose example I included in the working fiddle is:

$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 array returned is a response status of 200, an empty response body, and an empty set of headers (i.e. use the defaults).

I also added a whenGET so you can see them working together:

$httpBackend.whenGET('/phones').respond(function(method,url,data) {
  console.log("Getting phones");
  return [200, phones, {}];
});
like image 136
Josh David Miller Avatar answered Nov 24 '22 06:11

Josh David Miller