Skip to content

Instantly share code, notes, and snippets.

@walterg2
Last active August 29, 2015 14:16
Show Gist options
  • Save walterg2/19eb07a058e8148895f0 to your computer and use it in GitHub Desktop.
Save walterg2/19eb07a058e8148895f0 to your computer and use it in GitHub Desktop.
How do you mock out the HTTP Backend that is called from a service, but responses are used inside a controller in Angular

Problem

Want to create a service that holds all of our HTTP calls, but to test the controller that is using that service, how do we allow the ability to pass through to the real service, but mock out the HTTP calls to the server?

myapp.controller('myController', ['myService', function (myService) {
$scope.autofillSearch; //Input field in HTML
$scope.findAutofill = function () {
myService.autofill($scope.autofillSearch)
.success(function () {
window.console.log('Yay!');
})
.error(function () {
window.console.log('BOOO!');
});
}
}]);
myapp.factory('myService', [$http, function($http) {
return {
autofill: function (request) {
$http.post('/some/url', request);
}
}
}]);
@DonAbney
Copy link

In the past, I have wrapped the app with a mock in the spec. Maybe this helps if I understand the question? LMK

browser.addMockModule('SomeDumbHTTPMock', function() {
angular.module('SomeDumbHTTPMock', ['ngMockE2E', 'SomeDumbApp']).run(function($httpBackend) {
var error = 'there was an error.';
$httpBackend.whenGET('http://localhost:11000/xxx/xxxxx).respond(404, error);
$httpBackend.whenGET('http://localhost:11000/xxxx/ping/index.html').respond(200, '');
$httpBackend.whenGET(/.*/).passThrough();
});
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment