jeudi 28 avril 2016

Angular testing of a failing promise

I am trying to test a failing promise

service 'resolveService' function:

     return {resolveRedirect: function(){
                var deferred = $q.defer();
                  $http.jsonp('randomUrl')
                    .then(function(response){
                      jsonpResponse.responseHandler(response.data);
                      deferred.resolve(1);
                    }, function(err){
                      jsonpResponse.responseHandler({});
                      deferred.resolve(err);
                    });
                return deferred.promise;
              },
           }

I want the test a failing promise and wrote the following:

    spyOn(jsonpResponse,'responseHandler');

    $httpBackend.expectJSONP('randomUrl').respond(400, {});

    var promise = resolveService.resolveRedirect();

    var result;

    promise.then(function(data){
      console.log('we are in success');
      expect(true).toEqual(false);
    },function(err){
      console.log('we are in error');
      result = err;
      expect(result).toEqual(err);
    });

    $httpBackend.flush();
    expect(jsonpResponse.responseHandler).toHaveBeenCalledWith({});

When running this test, it fails by saying that expect(true).toEqual(false); is wrong. Also the console tells me, that the promise acutally succeeds and prompts 'we are in success'.

Where am I wrong? As I am expecting a 400 error, the promise should fail and the test should pass right?

Aucun commentaire:

Enregistrer un commentaire