Seeking guidance after struggling with unit testing an angular service, specifically the failed part of a 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);
});
}
};
}]);
}());
Despite reviewing multiple resources on Stack Overflow, I am unable to successfully test a rejected promise. I have attempted various approaches but none have produced the desired outcome. Here is the current setup:
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 handle error appropriately", 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();
// Assertion goes here but result is consistently incorrect
});
Understanding the asynchronous nature of promises, I've pieced together information from various sources. However, I welcome any advice or suggestions on how to effectively complete this unit test.