jeudi 21 mai 2015

How to properly mock an Angular Promise returned from $http

I have been fighting with this for a little bit now and need some guidance. I would like to unit test this angular service... specifically, the failed part of the promise.

(function () {
angular.module('testable')
    .factory('myService', ["$http", "$q", function ($http, $q) {
        return {
            createThing: function(thing) {
                return $http.post("//...", thing)
                        .then(function (response) {
                            return response.data;
                        }, function (response) {
                            return $q.reject(response.statusText);
                        });
            }
        };
    }]);
}());

I have been through a number of SO posts about this but each one seems to be a little different. First of all, if any of my service code is not correct in setting up the promise, please stop me there. I have been through about 10 different iterations of testing a rejected promise but nothing is working. Here is what I have:

    beforeEach(inject(function ($injector,myService) {
        sut = myService;
        $httpBackend = $injector.get('$httpBackend');
        $q = $injector.get('$q');
        $rootScope = $injector.get('$rootScope');
        dataToSend = "send me!";
        deferred = $q.defer();
    }));

    it("should get error on error", function () {
        var result,
            expected = "FAIL!!!!!";

        deferred.reject(expected);
        $httpBackend.expectPOST(testUrl,dataToSend).respond(deferred.promise);

        sut.createThing(dataToSend).then(function (returnFromPromise) {
            result = returnFromPromise;
        });

        $rootScope.$apply();
        $httpBackend.flush();

        // expect something here but result is always wrong
    });

I understand that promises run asynchronously... and I have been cobbling together tidbits of info, but does anyone have advice for completing this unit test?

Aucun commentaire:

Enregistrer un commentaire