3

Due to some infrastructure changes (namely servers & VPNs) there are times I want to run our application in an offline mode. I've been able to implement this with ngMockE2E however it seems to be an all or nothing approach, meaning you have to explicitly set every single HTTP request out of the app.

Is there a way to have it assume that unless you have explicitly set a route/url to be handled that it will automatically call a generic passThrough() operation?

Currently I am doing this:

noSrvc = $location.search().hasOwnProperty 'nosrvc'

#
# templates
#
$httpBackend.whenGET /(\.htm|\.html)$/
.passThrough();

#
# session
#
rqst = $httpBackend.whenGET /(api\/users\/current)$/
if !noSrvc then rqst.passThrough() else rqst.respond {"user":{

# doing something similar for every single service call in the app... gets tedious after about 3-4

Most everything I've read on the subject deals with unit testing and doesn't really address the implied passthrough unless otherwise stated.

jusopi
  • 6,791
  • 2
  • 33
  • 44

1 Answers1

2

That's the recipe I've used for whitelisting

app.run(function ($httpBackend) {
    // mocked requests, should come first
    $httpBackend.when('GET', 'mock').respond(200, {});

    // whitelisted real requests, should come last
    angular.forEach(['GET', 'DELETE', 'JSONP', 'HEAD', 'PUT', 'POST', 'PATCH'], function (method) {
        $httpBackend.when(method).passThrough();
    });
});

And I'm quite sure that precedence matters here.

Estus Flask
  • 206,104
  • 70
  • 425
  • 565
  • by precedence you mean that you are establishing those URLs that you want to have mock data to first, then the *otherwise* condition last? I will try this tomorrow. Looks super easy, thanks – jusopi Oct 21 '15 at 01:55
  • @jusopi Yes, it evaluates the conditions in that order IIRC. – Estus Flask Oct 21 '15 at 07:09
  • Finally got to test this and it works great. Simplified a bunch of nasty, hard-to-read if/else blocks into a condensed chuck of code. Thank you. – jusopi Oct 21 '15 at 19:27
  • yeah it's really annoying that the precedence matters :( it makes it really ugly when working with protractor an jasmine, ideally you would like to put your passThrough() stuff in beforeAll() function and only the mocked ones in the test (it) but because of precedence you have to include both in each test :( – IronHide Dec 07 '16 at 07:54
  • @IronHide You can always do something to reach the desired behaviour with the least amount of code. E.g. to make a helper function or service that defines all provided request mocks and does `passThrough()` afterwards, or to decorate `$http` to do `passThrough()` automaticaly on the first request. It would be convenient to have built-in 'passthrough' mode for `$httpBackend` but this can be fixed with a bit of developer's effort. – Estus Flask Dec 07 '16 at 08:33