Search code examples
angularjshttpbackendangularjs-ngmockngmocke2e

angular $httpBackend.when mocks - delay response NOT globally


I found this article how to create an artificial server delay when using $httpBackend for mocking data.

Is there any way at all to have this on a per-mock basis? Perhaps something like:

    $httpBackend
        .whenGET(/\/my\/endpoint$/)
        .respond(data, 2000);

OR

   $httpBackend
        .whenGET(/\/my\/endpoint$/)
        .withDelay(2000)
        .respond(data);

Solution

  • You can use angular-mocke2e-maydelay

    if you use bower

    bower install angular-mocke2e-maydelay
    

    in index.html

    <script src="/bower_components/angular-mocks/angular-mocks.js">    </script>
    <script src="/bower_components/angular-mocke2e-maydelay/angular-mocke2e-maydelay.js"></script>
    

    Add this to your app

    angular.module('app', ['ngMockE2E', 'mayDelay'])
    

    In the tests the unmocked $httpBackend can be used as below to delay the response.

    $httpBackend.whenGET('/foo.json').respond({foo:"bar"}, 3000); //delay 3s
    $httpBackend.whenPOST('/bar',{foo:"bar"}).respond(200, "succeed", 5000); //delay 5s
    

    This feature request is already posted in the angularjs repo