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

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

Posted by: admin January 30, 2018 Leave a comment


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.:


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


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.


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);
  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, {}];