dimanche 28 février 2016

How to mock the http connection error in $http unit testing in angular

Is there a way to simulate a connection error in an AngularJS unit test? I'm currently using jasmine and I mock connections to my service using $httpBackend. I know I can force a specific response code (such as 500) for a specific test if I want to simulate a service error. But I want to simulate a connection error, in order to test the "catch" part of the $http promise.

An example of the code I'd like to test:

  var getItemList = function() {
    return $http.get(API_BASE_URL + '/api/items')
      .then(function(response) {
        //I would check the response code and handle service errors here
        return response.data;
      })
      .catch(function() {
        return []; //I want to test the code I place in this catch
      });
  };

Is there a way to do that?

Aucun commentaire:

Enregistrer un commentaire